理解 async/await 的执行

 这是一篇简单的短文章,方便理解。

开局先丢官宣:

console.log(1); async function async1(){      console.log(2);      await async2();      console.log(3); };  async function async2(){ console.log(4)};  async1(); console.log(5);  // 输出结果 1 2 4 5 3
复制代码

理解一下输出结果:

第一步:输出 1;

第二步:输出 2,async1 先被调用,肯定优先于函数内的console和后面的console.log(5);

第三步:输出 4,把 await async2() 转为 promise 形式:

复制代码
    new Promise(resolve => {         console.log('2')         resolve();     }).then(res => {         // 抽出 await 之后的代码放到.then        console.log(3);     });
复制代码

这时候先输出 2,再等 3 的输出。

但由于 3 在Promise规范里被设定为异步(划重点: ES6中属microTask ,此处直接影响低版本中对promise实现的shim ),且await表示遇到await关键字后先将这块代码的asyncContext挂起并执行上级上下文,所以先执行了5,于是...

第四步:输出 5,执行完后回到 async context,再于是...

第五步:最后输出 3。

例二

在官宣上没看到  依次向上  字样鸭,咋肥事?继续代码:

复制代码
console.log(1); function fn1(){     function fn2(){         async function async1(){              console.log(2);             await fn3();             console.log(3);         }          function fn3(){ console.log(4); }         async1();         new Promise(resolve => resolve(5)).then(res => console.log(res));         console.log(6);     }     fn2();     console.log(7); } fn1(); console.log(8); // 输出结果 1 2 4 6 7 8 3 5
复制代码

理解一下输出结果:

第一步:输出 1;

第二步:fn1 被执行,fn2 被执行,输出 2;

第三步:fn3 被执行,如第一例所述,输出 4;

第四步:async context 被挂起,将 fn2 上下文作为运行上下文,输出 6;

第五步:fn2 上下文处理后继续向外更新,fn1 上下文作为运行上下文,输出 7;

第六步:重复上述,输出 8;

第七步:由于 fn3 的await(promise)在 fn2 中的 new Promise 前被加入执行列队,根据先进先出的执行顺序,输出 3;

第八步:最后输出 5。

例三

如果2个 async 嵌套顺序是啥样的呢?再看代码:

复制代码
                        
关键字:
50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信