Callbacks, promises and the event loop
Node.js runs your JavaScript on a single thread, yet one Node server can handle thousands of requests at the same time. The secret is non-blocking I/O and the event loop. Understanding them is the key to writing fast, correct Node code.
Blocking vs non-blocking
When a program reads a file or queries a database, it spends most of that time waiting. A blocking program sits idle during the wait. Node instead starts the operation, carries on with other work, and runs your code again when the result is ready:
Line 2 prints before the file contents: Node didn't wait for the disk.
Three ways to handle results
1. Callbacks (the original style)
Node's oldest APIs take a callback: a function called when the work is done, with an error as the first argument (null when it succeeded):
Each step nests inside the previous one. With five steps, this becomes the infamous callback pyramid, hard to read and easy to get wrong.
2. Promises
A promise is an object representing a result that will arrive later. Chain steps with .then() and handle errors once with .catch():
3. async/await (use this)
async/await is syntax on top of promises. The code reads top to bottom, and errors are handled with ordinary try/catch:
Converting callbacks to promises
Older libraries may only offer callbacks. util.promisify wraps a callback-style function into one that returns a promise:
Doing things in parallel
await inside a loop runs the operations one after another. When they don't depend on each other, start them all and wait for all of them with Promise.all:
| Helper | Resolves when | Rejects when |
|---|---|---|
Promise.all(list) |
All succeed (gives all results) | Any fails |
Promise.allSettled(list) |
All have finished, success or not | Never |
Promise.race(list) |
The first one settles | The first one fails |
Promise.any(list) |
The first one succeeds | All of them fail |
The event loop
How does one thread juggle all of this? Node keeps queues of work that's ready to run, and the event loop repeatedly takes the next item and runs it:
┌──────────────────────────┐
┌─>│ timers │ setTimeout / setInterval callbacks that are due
│ ├──────────────────────────┤
│ │ poll (I/O) │ finished file, network and database operations
│ ├──────────────────────────┤
│ │ check │ setImmediate callbacks
│ └──────────────────────────┘
│ after every callback: process.nextTick queue, then promise callbacks
└──────────────── repeat while anything is pending ───────────────Synchronous code always runs to completion first. Then microtasks (promise callbacks and process.nextTick) run, and only then the next macrotask (timers, I/O, setImmediate):
In an ES module like this one, the promise callback runs before
process.nextTick; in a CommonJS file those two swap. And when called from the main program,setTimeout(fn, 0)andsetImmediate(fn)can run in either order. Real code should never depend on these fine details: if B must happen after A, call B when A is done.
Node exits when the event loop has nothing left to do: no timers, no pending I/O, no open servers.
Never block the event loop
Because there's one thread, a long synchronous computation stops everything: timers, requests, all of it:
In a web server, that loop would make every user wait. For heavy CPU work, split it into chunks, move it to a worker thread (node:worker_threads), or hand it to another service.
Practice
- Write
wait(ms)that returns a promise resolving aftermsmilliseconds, then use it to print "3", "2", "1", "Go!" one second apart. - Use
Promise.allto read three files at once and print their total length. - Predict the output order of a program mixing
setTimeout(…, 0),setImmediate,Promise.resolve().thenand twoconsole.logcalls, then run it to check.
1.What does await do inside an async function?
2.Three independent API calls take 300 ms each. Roughly how long does await Promise.all([...]) take?
3.Why is a long while loop dangerous in a Node web server?