以下代码的输出顺序是什么?解释原因。

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')
}, 0)

async1()

new Promise((resolve) => {
  console.log('promise start')
  resolve()
}).then(() => {
  console.log('promise then')
})

console.log('script end')

输出结果

script start
async1 start
async2
promise start
script end
async1 end
promise then
setTimeout

详细分析

1. 同步代码执行

2. 微任务队列执行

3. 宏任务队列执行

核心规则

同分类其他题目