例题
async function async1() {
console.log('async1 start')
await async2();
console.log('async1 end')
}
async function async2() {
console.log('async2')
}
console.log('script start')
setTimeout(function () {
console.log('setTimeout')
}, 0)
async1();
new Promise((resolve) => {
console.log('promise1')
resolve();
}).then(() => {
console.log('promise2')
})
console.log('script end')
执行结果如下
解析:
执行顺序是同步任务–>微任务–>宏任务,只有上游的任务全部执行完才能执行下游的任务。async标记的函数会原地等待await表达式的结果,await表达式后面的内容就相当于then里面的内容,属于异步的微任务。
---任务栈---
script start
async1 start
async2
promise1
script end
---微任务队列---
async1 end
promise2
---宏任务队列---
setTimeout
变式一
async function async1() {
console.log('async1 start')
await async2();
await async3();
console.log('async1 end')
}
async function async2() {
console.log('async2')
}
async function async3() {
console.log('async3')
}
console.log('script start')
setTimeout(function () {
console.log('setTimeout')
}, 0)
async1();
new Promise((resolve) => {
console.log('promise1')
resolve();
}).then(() => {
console.log('promise2')
})
console.log('script end')
结果:
解析:注意这题有微任务的嵌套,同一个async标记的函数中若有多个await,那么就存在微任务的嵌套(微任务套着微任务)。
先将任务按照顺序分好类
首先执行同步任务,所以依次输出
此时状态如下
再执行如下微任务
先执行await async3()
,控制台输出async3,注意await async3()
后面的内容又是一个微任务,所以console.log('async1 end')
添加进微任务队列
此时状态如下
然后按照微任务–>宏任务的顺序执行,所以再依次输出:
变式三
async function async1() {
console.log('async1 start')
await async2();
await async3();
console.log('async1 end')
setTimeout(function () {
console.log('async4')
}, 0)
}
async function async2() {
console.log('async2')
}
async function async3() {
setTimeout(function () {
console.log('async3')
}, 0)
}
console.log('script start')
setTimeout(function () {
console.log('setTimeout')
}, 0)
async1();
new Promise((resolve) => {
console.log('promise1')
resolve();
}).then(() => {
console.log('promise2')
})
console.log('script end')
结果
解析:按照变式二解析的思路去推导即可得出