π§ 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.