wrong action
function asyncfunc() { let ret = 100; setTimeout(() => { return ret; }, 1000) } let ret = asyncfunc() console.log(ret) // undefined
callback
function asyncfunc(callback) { let ret = 100; setTimeout(() => { callback(ret) }, 1000) } function callback(ret) { // 处理异步获取的数据 console.log(ret) } asyncfunc(callback)
promise
function asyncfunc() { let ret = 100 return new Promise(function(resolve) { setTimeout(() => { resolve(ret) }, 1000) }) } asyncfunc().then(value => { // 处理异步获取的数据 console.log(value) })
generator
function asyncfunc() { let ret = 100 setTimeout(() => { it.next(ret) }, 1000) } function *gen() { let ret = yield asyncfunc() // 处理异步获取的数据 console.log(ret) } let it = gen() it.next()
generator + promise
function asyncfunc() { let ret = 100 return new Promise(resolve => { setTimeout(() => { resolve(ret) }, 1000) }) } function *gen() { let ret = yield asyncfunc() // 处理异步获取的数据 console.log(ret) } let it = gen() it.next().value.then(value => { it.next(value) })
async/await
function asyncfunc() { let ret = 100 return new Promise(resolve => { setTimeout(() => { resolve(ret) }, 1000) }) } (async function() { let ret = await asyncfunc() // 处理异步获取的数据 console.log(ret) })()
所有的异步代码必须写在 new Promise 的逻辑里
如果你想获取一个 async 函数的结果,你需要使用 Promise 的 then 语法:(async 函数的执行结果会自动变成一个 Promise)
async function doubleAndAdd(a, b) { a = await doubleAfter1Sec(a) b = await doubleAfter1Sec(b) return a + b } function doubleAfter1Sec(param) { return new Promise(resolve => { setTimeout(() => resolve(param * 2), 1000) }) } doubleAndAdd(1, 3).then(console.log) // 8
在上面的例子中,我们显示地调用了 await 两次,因为每次都等待了 1 秒钟,因此总计两秒钟。现在,我们可以使用 Promise.all 函数来让他们并行处理。
async function doubleAndAdd(a, b) { [a, b] = await Promise.all([doubleAfter1Sec(a), doubleAfter1Sec(b)]) return a + b } function doubleAfter1Sec(param) { return new Promise(resolve => { setTimeout(() => resolve(param * 2), 1000) }) } doubleAndAdd(1, 3).then(console.log) // 8