promise、async和await的执行顺序

搞不清楚js的执行顺序,直到遇到了下面这个题目,现在已经会分析了

 

这个题目需要分析js的事件循环和回调队列

打印顺序是什么:

async function async1() {
  console.log('1');
  console.log(await async2());
  console.log('2');
}

async function async2() {
  console.log('3');
  return '0';
}

setTimeout(function () {
  console.log('4');
  new Promise(function (resolve) {
    console.log('5');
    resolve();
  }).then(function () {
    console.log('6')
  })
});

async1();

new Promise(function (resolve) {
  console.log('7');
  resolve();
}).then(function () {
  console.log('8');
});

console.log('9');

 

    执行解析:
    async1和async2都是函数,需要调用才会执行
    setTimeout为宏任务,会进入宏任务队列等待执行

    async1函数被调用,立即执行里面的console.log('1');
    执行console.log(await async2())的时候,async2函数被调用,立即执行里面的console.log('3');
    此时async2函数中的return '0' 会进入微任务队列,async1函数中的console.log('2')也进入微任务队列
    执行new Promise中的console.log('7'),new Promise中的then函数进入微任务队列

    执行console.log('9')

    以上第一轮可以立即执行的任务执行结束

    第二轮开始执行依次微任务队列
    先看微任务队列里面待执行的任务
    async2函数中的return '0'
    async1函数中的console.log('2')也进入微任务队列

    执行async2函数中的return '0',即console.log(await async2()) = console.log('0')
    执行async1函数中的console.log('2')
    执行new Promise中的then函数,console.log('8');

    第二轮执行结束

    第三轮继续执行微任务


    第三轮执行结束

    开始执行宏任务
    执行console.log('4');
    执行console.log('5');
    执行console.log('6');

    打印结果
    1 3 7 9 0 2 8 4 5 6

 

posted @ 2021-02-05 11:19  深lin人不知  阅读(163)  评论(0)    收藏  举报