async function async1() {
console.log("a");
await async2();
console.log("b");
}
async function async2() {
console.log("c");
await async3();
console.log("zzzzz");
}
const async3 = async () => {
console.log("qqqq");
};
console.log("d");
async1();
setTimeout(() => {
console.log("e");
}, 0);
new Promise((resolve, reject) => {
console.log("f");
resolve();
}).then(() => {
console.log("g");
});
.as-console-wrapper { max-height: 100% !important; }
Here’s what I envisioned:
d, a, c, qqqq, f, zzzzz, b, g, e。
But the order in which it runs in the browser is:
d
a
c
qqqq
f
zzzzz
g
b
e
After the first execution completes, the microtask queue should be console.log("zzzzz"); console.log("b"); console.log("g");
The order of execution is, zzzzz b g, but the result in the browser is not like this, is there something I’m thinking wrong?
extremely grateful!
2
Answers
"b" is not in the queue. The promise returned by
async2
has not yet resolved.When synchronous code finishes, there are two promises in the resolved state: the one returned by
async3
, and the one created bynew Promise
. So the microtask queue contains 2 things: resumingasync2
(ie,console.log("zzzzz")
) and the anonymous.then
callback (ie,console.log("g")
).async2
resumes, logs "zzzzz", then returns (which resolves its promise). A microtask is queued up to resumeasync1
(ie,console.log("b")
), but it must go to the end of the queue. Next the.then
callback runs, logging "g". And only after that canasync1
resume and log "b".Output:
d
a
c
qqqq
zzzzz
b
f
g
e
This sequence is based on the understanding of asynchronous behavior in JavaScript. The async/await syntax, setTimeout, and Promise callbacks contribute to the order of execution. If you have any further questions or need additional clarification, feel free to ask!