JavaScript · Question 86
What is the output order when queueMicrotask(), Promise.then(), and setTimeout() schedule work inside one another?
Direct answer
Microtasks are drained in queue order, including microtasks appended while the checkpoint is running; timer callbacks are later tasks, and each such task can create another microtask checkpoint before the next task runs.
console.log("A");
queueMicrotask(() => {
console.log("B");
Promise.resolve().then(() => console.log("C"));
});
Promise.resolve().then(() => {
console.log("D");
queueMicrotask(() => console.log("E"));
});
setTimeout(() => console.log("F"), 0);
console.log("G");A G B D C E F
Consider console.log("A"); queueMicrotask(() => { console.log("B"); Promise.resolve().then(() => console.log("C")); }); Promise.resolve().then(() => { console.log("D"); queueMicrotask(() => console.log("E")); }); setTimeout(() => console.log("F"), 0); console.log("G");.
The synchronous output is A, G. The first queued microtasks are the callback printing B and the Promise reaction printing D, so they run as B, D. While those run they append C and E to the same microtask queue, which are then drained as C, E. Only after that checkpoint can the timer task print F. Final order: A, G, B, D, C, E, F.
- Both Promise reactions and
queueMicrotask()schedule microtask-style work in the browser event-loop model. - Microtasks scheduled by earlier microtasks are appended and still run before moving on to the later timer task.
- Do not infer ordering merely from which API call appears “more asynchronous.” Track the actual queue each callback enters.