代码片段如下所示:
console.log('test')
async function async1() {
console.log('before wait');
await wait();
console.log('after wait');
}
async function wait() {
try {
return await new Promise((res, rej) => {
console.log('wait');
rej('reject');
});
} catch (reason) {
console.log(reason);
}
}
async function test() {
async1();
console.log('before resolve');
await Promise.resolve();
console.log('after resolve');
}
test();
console.log('test end');
您还可以在playground中运行代码
实际结果:
[LOG]: "test"
[LOG]: "before wait"
[LOG]: "wait"
[LOG]: "before resolve"
[LOG]: "test end"
[LOG]: "reject"
[LOG]: "after resolve"
[LOG]: "after wait"
我以为after wait
会先打印,因为它很早就被推入微任务队列中了?
我哪里错了?
我听取了@Seblor的建议
如果您用THEN函数替换异步/等待,情况可能会变得更清楚.
然后,我删除了所有的异步/等待
console.log('test')
function async1() {
console.log('before wait');
return wait().then(() => {
console.log('after wait');
})
}
function wait() {
return new Promise((res, rej) => {
console.log('wait');
rej('reject');
}).catch((reason) => {
console.log(reason);
})
}
function test() {
async1();
console.log('before resolve');
Promise.resolve().then(() => {
console.log('after resolve');
})
}
test();
console.log('test end');
然后我意识到推送到微任务队列中的第一个代码是catch
中的代码,然后是console.log('after resolve')
,最后是console.log('after wait')