备注,当修改代码为
async function async1() {
console.log('async1 start')
const a = await async2()
console.log('async1 end', a)
}
async function async2() {
console.log('async2')
return new Promise((resolve) => { console.log('async2 return success'); resolve(1) })
}
console.log('script start')
setTimeout(function () {
console.log('setTimeout')
}, 0)
async1();
new Promise(function (resolve) {
console.log('promise1')
resolve();
}).then(function () {
console.log('promise2')
})
console.log('script end')
执行顺序为
script start
async1 start
async2
promise1
script end
promise2
async1 end 1
async1 end
setTimeout
证明一个事实:
await 后的async函数会先执行,如果没有返回promise,会默认返回一个resolve(undefined)的promise对象,但是此时还没有调用then,会跳出当前await所在的async函数,等到本轮所有其他同步代码执行完毕后,回到await,此时await等同于调用then方法,即将一个微任务推到本轮微任务队列中,所以为什么promise2比async1 end 1先打印,因为打印promise2的那个promise对象先于await执行了then方法,所以它对应的微任务先推进去。