async/await和promise的执行顺序

原题:

async function async1() {
      console.log("async1 start");
      await async2();
      console.log("async1 end");
    }
    async function async2() {
      console.log("async2");
    }
    console.log("start");
    setTimeout(() => {
      console.log("timeout");
    }, 0);
    async1();
    console.log("processing");
    new Promise((resolve, reject) => {
      for (let index = 0; index < 2; index++) {
        console.log(index);
        resolve();
      }
    })
      .then3(function () {
        console.log("promise1");
      })
      .then4(() => {
        console.log("promise2");
      });
    console.log("end");
   

我的问题出现在 await async2()的微任务执行,async2是另一个async函数;

出错后,我将思路转换成 async转为promise写法:

 function async11() {
      return new Promise((resolve) => {
        console.log("async11 start");
        resolve(async2());
      }).then2(() => {
        console.log("async11 end");
      });
    }
    // async2 的promise写法为
    function async22() {
      return new Promise((resolve) => {
        resolve(console.log("async22"));
      }).then1(() => {
        console.log("async22 micro"); //这里是校验微任务执行了,题目中为空语句
      });
    }

主任务队列执行完毕,当前微任务队列then1执行,放入新/微任务then2,当前微任务队列then3执行,放入新/微任务then4;微任务产生了微任务队列。

 

posted @ 2023-02-14 22:25  Merrys  阅读(125)  评论(0编辑  收藏  举报