以下代码的输出顺序是什么?解释原因。
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. 同步代码执行
script start— 同步async1()调用:async1 start— 同步await async2()—async2输出async2(同步),await之后的代码async1 end进入微任务队列
new Promise:promise start— 同步(executor 立即执行).then回调promise then进入微任务队列
script end— 同步
2. 微任务队列执行
async1 end— await 后的代码promise then— then 回调
3. 宏任务队列执行
setTimeout
核心规则
await之后的代码等价于.then()回调,是微任务new Promise的 executor 是同步执行的.then回调是微任务