Advanced Node.js Interview QuestionsAdvancedCode Output
Node.js · Question 89
What is the output of nested Promise microtasks?
Direct answer
Output: 1, 5, 2, 3, 4 — sync first; microtasks drain fully (including nested .then) before macrotasks; each Promise.then queues one microtask.
promise-microtasks.mjs
console.log("1");
Promise.resolve().then(() => console.log("2"));
Promise.resolve().then(() => {
console.log("3");
Promise.resolve().then(() => console.log("4"));
});
setTimeout(() => console.log("timeout"), 0);
console.log("5");Output
1 5 2 3 4 timeout
The microtask queue drains completely before the timers phase — nested Promise in the second .then schedules 4 before timeout runs.
- Sync — 1, 5.
- First microtask batch — 2 from first Promise; 3 from second.
- Nested microtask — 4 queued during 3's callback, runs before leaving microtask checkpoint.
- Macrotask — timeout last.