Appearance
EventLoop 解析
题目
js
console.log(1)
async function fn1() {
console.log(2)
await fn2()
console.log(3)
return 4
}
fn1().then(fn4)
.then((res) => {
console.log(res)
})
fn3().then((res) => {
console.log(res)
})
async function fn2() {
console.log(5)
setTimeout(() => {
console.log(6)
})
}
function fn3() {
console.log(7)
return new Promise((resolve, reject) => {
console.log(8)
setTimeout(() => {
resolve(9)
})
})
}
function fn4(num) {
console.log(num)
return new Promise((resolve, reject) => {
console.log(10)
resolve(11)
})
}
解题思路
顺时针循环,从内到外观察 ,先循环微任务,然后再执行宏任务,要把执行的整段代码作为一个整体来阅读,有可能出现宏任务包裹着宏任务, 那么这就是宏任务队列.
最后微任务彻底清空了,才轮到宏任务,从上至下逐一打印(先进先出)