关于async/await输出顺序的题

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');
  })
}

console.log('script start');

setTimeout(function() {
  console.log('setTimeout');
}, 0);

async1();

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

为什么打印顺序是promise2-promise3-async1 end,而不是promise2- async1 end - promise3呢?

阅读 3.4k
3 个回答
  1. 去掉所有同步干扰
  2. 去掉 async 语法糖

你的题目等价于

new Promise(resolve => resolve(Promise.resolve())).then(() => {
  console.log('async1 end')
})

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

最终问题转变为 new Promiseresolve 如果传入的是一个 Promise 将要怎么处理,这个问题可以参考

如何理解 resolve(Promise.resolve())内部执行了什么?

具体 C++ 内部如何实现的,我也不甚了解

尝试下把async 改成promise

   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()
    
    改成的promise,如下,替换后运行结果一样
    new Promise(function(resolve) {
      console.log('async1 start')
      resolve(
        new Promise(function(resolve2) {
          console.log('async2 start')
          resolve2(
            new Promise((resolve3, reject) => {
              resolve3()
              console.log('async2 promise')
            })
          )
        })
      )
    }).then(function() {
      console.log('async1 end')
    })

image.png

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

这段代码中then的回调返回的不是Promise,相当于下面代码

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

改写成下面这样可以达到你想要的的效果

new Promise(function (resolve) {
    console.log('promise1');
    resolve();
}).then(function () {
    return Promise.resolve(console.log('promise2'))
}).then(function () {
    console.log('promise3');
});
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏