Predict the output · Node.js
Microtasks vs Macrotasks
Medium Predict the output Most askedSeen at Meta, Netflix, Vercel, Microsoft
In what order are the letters printed?
What does this print?
console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => console.log("C"));
queueMicrotask(() => console.log("D"));
(async () => {
console.log("E");
await null;
console.log("F");
})();
console.log("G");
A B C D E F G
A E G C D F B
A G E C D B F
A E G B C D F
Check your answer
Loading the editor… (JavaScript is required to run code in your browser.)
Solution
Show the answer
The output is:
A E G C D F B
- Synchronous code runs first:
A, then the async function body runs synchronously up to its firstawait(E), thenG. - The microtask queue drains next, in the order tasks were queued: the
.thencallback (C), thequeueMicrotaskcallback (D), then the continuation afterawait null(F). - Only then does the event loop take the next macrotask — the
setTimeoutcallback (B), even with a 0 ms delay.
More Gotchas problems
- var in a Loop with setTimeout · Easy
- Type Coercion Surprises · Medium
- Numeric Enums at Runtime · Medium
- Type Assertions Don't Convert · Easy
- readonly and as const at Runtime · Medium
- Mutable Default Arguments · Easy