🧠 Node.js Event Loop: Microtasks vs Macrotasks
📦 Example
Let's take a look at this short Node.js script:
console.log("1");
setTimeout(() => console.log("macrotask"), 0);
Promise.resolve().then(() => console.log("microtask"));
console.log("2");which outputs:
1
2
microtask
macrotask🔍 Sequence
This example demonstrates how Node.js handles asynchronous code within a synchronous workflow using the event loop, specifically:
- The Call Stack executes synchronous code line by line.
- The Microtask Queue (e.g. Promises,
await) runs after the stack is clear but before any macrotasks. - The Macrotask Queue (e.g.
setTimeout, I/O) runs after all microtasks are complete.
⚙️ Step-by-Step Breakdown:
console.log("1")→ runs immediately.setTimeout(..., 0)→ schedules a macrotask.Promise.resolve().then(...)→ queues a microtask.console.log("2")→ runs next (still in call stack).- Microtask (
console.log("microtask")) runs. - Macrotask (
console.log("macrotask")) finally runs.
✅ Key Takeaways
- Node.js is single-threaded but asynchronous.
- Microtasks always run before macrotasks once the call stack is empty.
