Predict the Output: async/await and the Microtask Queue
What does this log, and in what order? Explain why.
async function a() {
console.log("a1");
await null;
console.log("a2");
}
console.log("start");
setTimeout(() => console.log("timeout"), 0);
a();
Promise.resolve().then(() => console.log("then 1")).then(() => console.log("then 2"));
queueMicrotask(() => console.log("microtask"));
console.log("end");Hints
Hint 1
Sort each callback into one of two queues. Timers are tasks; promise callbacks and the code after an await are microtasks. After each task, every waiting microtask runs before the next task starts.
Hint 2
An async function runs synchronously until its first await.
Solution
Show the approach
Answer: start, a1, end, a2, then 1, microtask, then 2, timeout
An async function runs synchronously up to its first await; the rest of it is a microtask queued before then 1.
Assistant
Sign in to use the assistant — ask what the problem means, get a hint when you're stuck, or have your current work reviewed. Conversations save to your account.