Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

NO
Node.js & Express
0/13 completed
Beginner
What is Node.js?Modules and npmWorking with filesCallbacks, promises and the event loop
Intermediate
Events and streamsYour first HTTP serverExpress basicsRouting and middlewareConnecting a database
Advanced
Validation and configurationAuthentication with JWTTesting APIs
Pro
Deploying Node apps to production
Tracks / Node.js & Express / Beginner

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:

Node.js · editable

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):

Node.js · editable

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():

Node.js · editable

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:

Node.js · editable

Converting callbacks to promises

Older libraries may only offer callbacks. util.promisify wraps a callback-style function into one that returns a promise:

Node.js · editable

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:

Node.js · editable
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
Node.js · editable

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):

Node.js · editable

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) and setImmediate(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:

Node.js · editable

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

  1. Write wait(ms) that returns a promise resolving after ms milliseconds, then use it to print "3", "2", "1", "Go!" one second apart.
  2. Use Promise.all to read three files at once and print their total length.
  3. Predict the output order of a program mixing setTimeout(…, 0), setImmediate, Promise.resolve().then and two console.log calls, then run it to check.
✎ Check your understanding

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?

← Working with files