async输出顺序的一道前端面试题疑问

新手上路,请多包涵
async function async1() {
      console.log('async1 start');
      await async2();
      console.log('async1 end');
    }
    
    async function async2() {
      console.log('async2 start');
      return new Promise((resolve, reject) => {
        resolve();
        console.log('async2 promise');
      })
    }

    async1();
    
    new Promise(function(resolve) {
      console.log('promise1');
      resolve();
    }).then(function() {
      console.log('promise2');
    }).then(function() {
      console.log('promise3');
    });

为什么输出顺序如下

async1 start
async2 start
async2 promise
promise1
promise2
promise3
async1 end

主要困惑是 async1 end 为什么在 promise3 后面?

阅读 2.5k
2 个回答

async1函数可以转化成下面这样

async function async1() {
    console.log('async1 start');
    console.log('async2 start');
    new Promise((resolve, reject) => {
        const thenable = new Promise((resolve2, reject2) => {
            resolve2();
            console.log('async2 promise');
        })
        new Promise((res, rej) => {
            thenable.then().then(resolve)
        })
    }).then(() => {
        console.log('async1 end');
    })
}

具体的分析这里有:https://segmentfault.com/q/10...

问题的关键在

async function async2() {
  console.log('async2 start')
  return new Promise((resolve, reject) => {
    resolve()
    console.log('async2 promise')
  })
}

可以用 Promise 做如下转换

async function async2() {
  console.log('async2 start')
  return new Promise((resolve, reject) => {
    resolve()
    console.log('async2 promise')
  })
}
// ->
function async2() {
  console.log('async2 start')
  const p = new Promise((resolve, reject) => {
    resolve()
    console.log('async2 promise')
  })
  return new Promise(function (resolve, reject) {
    Promise.resolve().then(() => {
      p.then(resolve)
    })
  })
}

更详细解释,可以看我的文章Async Function 背后的秘密

1 篇内容引用
推荐问题
宣传栏