the code snippet likes below:
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');
you can also run the code in playground
actual result:
[LOG]: "test"
[LOG]: "before wait"
[LOG]: "wait"
[LOG]: "before resolve"
[LOG]: "test end"
[LOG]: "reject"
[LOG]: "after resolve"
[LOG]: "after wait"
I thought after wait
would be printed first, since it is pushed in the micro task queue early?
where am I wrong?
I took advice from @Seblor
It may become clearer if you replace the async/await with the then function.
then I removed all the async/await
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');
Then I realized the first code pushed in micro task queue is the code in catch
, followed by console.log('after resolve')
, finally console.log('after wait')