6、异步任务打印顺序

43 阅读1分钟
async function async1() {
  console.log('async1 start')
  await async2()
  console.log('async1 end')
}

async function async2() {
  console.log('async2')
}

console.log('script start')

setTimeout(() => {
  console.log('setTimeout')
})

async1()

new Promise(resolve => {
  console.log('promise1')
  resolve()
}).then(() => {
  console.log('promise2')
})

console.log('script end')

// 打印结果:
// script start
// async1 start
// async2
// promise1
// script end
// async1 end
// promise2
// setTimeout

// 解析:
// await async2()
// console.log('async1 end') 这一行是 await 后面的,相当于回调,所以会放到微任务里面

参考资料:13、事件循环是什么? - 掘金