Async/Await in Node.js

Node uses non-blocking I/O: a slow job (such as reading a file) is started, and Node continues with other work. The result comes back through a callback (the…

A small coffee stall has just one barista. They take the first order, put the beans in the grinder, and while the grinder works on its own, they take the second order. When the grinder beeps, they go back to the first order. The queue keeps moving even with a single barista.

Node works the same way. The barista is JavaScript in Node: like the barista, JavaScript does one thing at a time. The grinder is the operating system, which does slow work such as reading a file. The beep is the sign that the result is ready. Code that starts a slow job (such as reading a file or asking a database), then does other work while it waits for the result, is called asynchronous (async) code.

Blocking and non-blocking

I/O (input/output) is any work that waits for something outside the program: the disk, the network, a database. Node uses a non-blocking I/O model: while one file is being read, Node can still answer other requests. A blocking barista stands staring at the grinder until it's done, and the queue behind them stops too. In Node, a blocking function also makes everything else wait. Its name ends in Sync, such as fs.readFileSync. On a server, use the versions that don't block.

Three ways to wait for a result

The three ways below do the same job: read data/notes.json in the notes-api project, then count the notes in it.

1. Callback, the oldest way. You hand over a function that is called later, when the file has been read:

const fs = require("node:fs");

fs.readFile("data/notes.json", "utf8", (err, content) => {
  if (err) {
    console.log("Failed: " + err.message);
    return;
  }
  console.log(JSON.parse(content).length + " notes");
});

When step two needs step one's result, step two's callback is written inside step one's callback, and so on. The code moves further and further to the right. These deeply nested callbacks are called callback hell.

2. Promise. fs.promises.readFile (the same as require("node:fs/promises").readFile) returns a Promise right away: an object promising that it will later succeed (resolve) with the file's contents or fail (reject) with an error. .then receives the result, and .catch receives the error:

fs.promises.readFile("data/notes.json", "utf8")
  .then((content) => console.log(JSON.parse(content).length + " notes"))
  .catch((err) => console.log("Failed: " + err.message));

3. async/await. Still the same Promise, but the code reads from top to bottom. await is only allowed inside a function marked async, and its error is caught with an ordinary try/catch:

async function countNotes() {
  try {
    const content = await fs.promises.readFile("data/notes.json", "utf8");
    console.log(JSON.parse(content).length + " notes");
  } catch (err) {
    console.log("Failed: " + err.message);
  }
}
countNotes();

All three print 2 notes. If the file is missing, all three print Failed: ENOENT: no such file or directory, open 'data/notes.json'.

await waits inside the function, Node keeps going

The number in each console.log below shows the order it prints in:

async function main() {
  console.log("1. start reading");
  const content = await fs.promises.readFile("data/notes.json", "utf8");
  console.log("3. done: " + JSON.parse(content).length + " notes");
}
main();
console.log("2. line after main()");

The output:

1. start reading
2. line after main()
3. done: 2 notes

await only pauses main until its Promise finishes. The code outside main keeps running, so line 2 is printed first. setTimeout works the same way: console.log("1"); setTimeout(() => console.log("2"), 0); console.log("3"); prints 1, 3, then 2. A callback, even with a delay of 0, only runs after all the synchronous code (ordinary lines that run one after another right away) has finished.

One after another, or at the same time

To make the time visible, we imitate slow work with delay: a setTimeout wrapped in a Promise. fetchNotes takes 300 ms, and fetchUsers takes 200 ms. How long do two awaits in a row take, and how long does Promise.all take? Calculate it before you look at the output.

function delay(ms, value) {
  return new Promise((resolve) => setTimeout(() => resolve(value), ms));
}
const fetchNotes = () => delay(300, ["Groceries", "Study"]);
const fetchUsers = () => delay(200, ["Budi"]);

async function main() {
  let start = Date.now();
  const notes = await fetchNotes();
  const users = await fetchUsers();
  console.log("one after another: " + (Date.now() - start) + " ms");

  start = Date.now();
  const [n2, u2] = await Promise.all([fetchNotes(), fetchUsers()]);
  console.log("Promise.all: " + (Date.now() - start) + " ms");
}
main();

The output:

one after another: 501 ms
Promise.all: 300 ms

Two awaits in a row wait one at a time: 300 + 200 = 500 ms. The numbers in the output can be a few ms higher each time you run it. Promise.all([...]) starts both at the same time and waits until all are done, so the total equals the slowest one, 300 ms. The result is an array in the same order as the list you gave it, not the order they finished in. So n2 holds the result of fetchNotes, even though fetchUsers finishes first.

Use Promise.all when the jobs don't depend on each other, meaning no job needs another job's result. If even one fails, Promise.all fails right away with that error. Need every result, the failed ones included? Promise.allSettled waits for all of them and gives each a status of fulfilled (succeeded) or rejected (failed).

In the exercise: fetchData and fetchWithError

In the exercise, the starter already has fetchData() (a Promise that succeeds with two items) and fetchWithError() (a Promise rejected with Connection timeout). In main():

  1. In the first try, change the Success: ... line to console.log("Data: " + JSON.stringify(data));.
  2. Under the comment // Complete the try/catch here, add a second try/catch. In the try, run await fetchWithError();. In the catch, print "Failed: " + err.message.

The expected output:

Fetching data...
Data: [{"id":1,"item":"Book"},{"id":2,"item":"Pencil"}]
Fetching data with an error...
Failed: Connection timeout

⚠️ An await that's forgotten, misplaced, or slow

TL;DR: Node uses non-blocking I/O: a slow job (such as reading a file) is started, and Node continues with other work. The result comes back through a callback (the old way, which easily turns into callback hell: deeply nested callbacks), a Promise (.then/.catch), or async/await with try/catch (the easiest to read). await only pauses its own async function, not the whole program. A setTimeout(..., 0) callback still waits until the synchronous code (ordinary lines that run right away) has finished, so print 1, timer 2, print 3 gives 1 3 2. fs.promises.readFile reads a file with a Promise. Two awaits in a row add up their times (jobs of 300 ms and 200 ms take 500 ms). Promise.all runs them together (300 ms) and fails right away if one fails. Take the error message from the caught err.message.

⚡ Wait with await, catch with try/catch

Write:

async function countNotes() {
  try {
    const content = await fs.promises.readFile("data/notes.json", "utf8");
    console.log(JSON.parse(content).length + " notes");
  } catch (err) {
    console.log("Failed: " + err.message);
  }
}

Meaning: Node uses non-blocking I/O: a slow job, such as reading a file, is started, and Node does other work while it waits. fs.promises.readFile returns a Promise, and await waits for its contents. await is only allowed in an async function, and its error is caught with an ordinary try/catch.

⚡ Only the function waits

Guess first: what does console.log("1"); setTimeout(() => console.log("2"), 0); console.log("3"); print, in order?

1, 3, then 2. Even with a delay of 0, the callback only runs after all the synchronous code (ordinary lines that run right away) has finished.

Meaning: await works the same way: it only pauses its own async function until the Promise finishes. The code outside that function keeps running.

⚡ At the same time with Promise.all

Write:

const [n2, u2] = await Promise.all([fetchNotes(), fetchUsers()]);

Meaning: fetchNotes() takes 300 ms and fetchUsers() takes 200 ms. Two awaits in a row wait one at a time: 300 + 200 = 500 ms. Promise.all starts both at the same time, so the total equals the slowest one, 300 ms. n2 and u2 get the results in the order of the array. If one fails, Promise.all fails right away.

What you will learn