async await
本身就是promise + generator
的語(yǔ)法糖。
本文主要講述以下內(nèi)容
- async awiat 實(shí)質(zhì)
- async await 主要特性
async await 實(shí)質(zhì)
下面使用 promise + generate 實(shí)現(xiàn) async await
// 轉(zhuǎn)換目標(biāo) async1
// async function async1() {
// console.log('async1 start');
// await async2();
// console.log('async1 end');
// }
function async1() {
// 將 async 轉(zhuǎn)換成 *,將 awiat 轉(zhuǎn)換成 yield
var awaitInstance = (function* () {
console.log('async1 start');
yield async2();
console.log('async1 end');
})()
// 自動(dòng)執(zhí)行 await 及后續(xù)代碼
// 簡(jiǎn)單起見(jiàn),不處理異常情況
function step() {
var next = awaitInstance.next();
// 使用Promise獲取 異步/同步 方法的結(jié)果,再執(zhí)行下一步
Promise.resolve(next.value).then(function (val) {
if (!next.done) step();
})
}
step();
// 返回Promise
return Promise.resolve(undefined);
}
async await 特性
- async 一定會(huì)返回 promise
// 案例1: 不設(shè)置return
async function fn() {}
fn().then(alert); // alert -> undefined
// 案例2:return非promise
async function f() {
return 1
}
f().then(alert); // alert -> 1
// 案例3: return Promise
async function fn() {
return Promise.resolve(2);
}
fn().then(alert); // alert -> 2
- async 中代碼是直接執(zhí)行的(同步任務(wù))
console.log(1);
async function fn() {
console.log(2);
await console.log(3)
console.log(4)
}
fn();
console.log(5);
// 打印 1 2 3 5 4
// 為何后面是 3 5 4 ? 往下看
- await是直接執(zhí)行的,而await后面的代碼是 microtask。
async function async1() {
console.log('async1 start');
await async2();
console.log('async1 end');
}
// 類(lèi)似于
async function async1() {
console.log('async1 start');
Promise.resolve(async2()).then(() => {
console.log('async1 end');
})
}
- await后面代碼會(huì)等await內(nèi)部代碼全部完成后再執(zhí)行
async function async1() {
console.log('async1 start');
await async2();
console.log('async1 end');
}
async function async2() {
return new Promise(function(resolve) {
setTimeout(function() {
console.log('sleep 2s');
resolve('do');
}, 2000)
})
}
async1();
// 打印結(jié)果
// async1 start -> sleep 2s -> async1 end
- await 操作符用于等待一個(gè)Promise 對(duì)象陕悬。它只能在異步函數(shù) async function 中使用。參考 MDN
附:
在chrome版本 73.0.3683.86(64 位)中,
await是可以直接使用的姆蘸。
var x = await console.log(1)
End
持續(xù)更新中 來(lái)Github 點(diǎn)顆?吧