Event Loop & Async
What is the Event Loop?
Section titled “What is the Event Loop?”JavaScript in Node.js runs on a single thread. Yet it can handle thousands of simultaneous connections without blocking. The secret is the event loop — a mechanism that delegates slow work (file reads, network calls) to the operating system, then processes the results when they arrive.
At its core, the runtime has three key structures:
- Call stack — where synchronous code executes, one frame at a time.
- Microtask queue — holds Promise callbacks and
queueMicrotaskcallbacks. Drains completely after every task. - Macrotask queue (task queue) — holds
setTimeout/setIntervalcallbacks. One macrotask is processed per event loop iteration.
The loop runs continuously: pick a macrotask → execute it → drain all microtasks → pick the next macrotask.
What this module covers
Section titled “What this module covers”| Lesson | Topic |
|---|---|
| Call Stack | Synchronous execution and why blocking matters |
| Callbacks | The original async pattern and Node’s error-first convention |
| Promises | States, chaining, and combinators |
| Async/Await | Reading async code like synchronous code |
| Microtasks & Macrotasks | Queue priorities and drain order |
| Timers | setTimeout, setInterval, and timer precision |
A first async demo
Section titled “A first async demo”The snippet below runs three pieces of code. Notice they do not execute top-to-bottom in the order written — the synchronous log fires first, the Promise callback fires next (microtask), and the setTimeout callback fires last (macrotask).
// What runs first?console.log('A — sync');Promise.resolve().then(() => console.log('B — microtask (Promise)'));setTimeout(() => console.log('C — macrotask (setTimeout)'), 0);Run it to confirm the order:
The output is always A, then B, then C — the event loop guarantees this ordering.