Thuta Learning
Node.js
IntermediateWeb DevelopmentBeginner

Asynchronous Node.js with Promises and async/await

Node.jsLesson 1430 min

What you'll walk away with

  • Explain the three Promise states: pending, fulfilled and rejected
  • Know that an async function always returns a Promise, and what exactly await pauses
  • Run independent work concurrently with Promise.all
  • Handle failures with try/catch, Promise.allSettled and an error cause

Explain it simply

Explain it simply

Think of a waiter in a restaurant. After passing an order to the kitchen, the waiter does not stand at the kitchen door until the dish is ready; they take orders at other tables and come back when the kitchen calls. Node's single thread works like that waiter: it hands file reads and database queries to the operating system and keeps serving other requests in the meantime.

A Promise is the ticket the kitchen hands back. There is no dish yet, but it promises an answer later: either the dish (a value) or "we ran out" (an error). await means "inside this function, continue only once this ticket is answered", while the waiter keeps doing other work.

Problem → Why → Solution

The problem: a missing await, and needless waiting in line

Two bugs dominate async code. The first is a missing await: readFile() returns a Promise immediately instead of the data, so JSON.parse() tries to parse the string "[object Promise]" and throws a SyntaxError. The second is awaiting independent work one item at a time: two 300 ms requests that could finish together in 300 ms take 600 ms, and every page gets slower.

slow-and-broken.mjs
import { readFile } from 'node:fs/promises';

const raw = readFile('./app.json', 'utf8');      // forgot await: a Promise
const config = JSON.parse(raw);
// SyntaxError: Unexpected token 'o', "[object Promise]" is not valid JSON

async function loadDashboard(id) {
  const user = await fetchUser(id);       // ~300 ms
  const orders = await fetchOrders(id);   // ~300 ms more, yet it never used user
  return { user, orders };
}

Why does this happen?

Calling a function that returns a Promise only starts the work; you get the result out with await (or .then()). await makes the following lines wait for that Promise, so two awaits in a row mean the second request only starts after the first finishes. Start both first and wait for them together with Promise.all, and they run at the same time.

Core concept: Promises, async and await

A Promise starts out pending and settles exactly once, either fulfilled with a value or rejected with an error; after that it never changes. Modern Node APIs such as fs/promises, fetch() and timers/promises return Promises instead of taking callbacks, and util.promisify() turns an older callback API into a Promise-returning function.

An async function always returns a Promise: write return 5 and the caller still receives a Promise of 5, and a throw inside becomes a rejected Promise. await promise pauses only that async function until the Promise settles; if it fulfilled you get the value, if it rejected the error is thrown right at that line. That is why ordinary try/catch works for async errors. While the function is paused, the event loop keeps running timers, other requests and callbacks; the thread itself is never blocked.

Four combinators wait on several Promises at once. Promise.all gives you an array of results in input order when all succeed, and rejects as soon as any one fails (without cancelling the others). Promise.allSettled waits for everything and reports each outcome. In ES module files you can use top-level await outside any function; in CommonJS, await only works inside an async function.

The other two are races. Promise.race takes the result or error of whichever Promise settles first, which makes it the usual way to build a timeout: race the work against a timer and fail if the timer wins. Promise.any takes the first success and rejects with an AggregateError only if every Promise fails, which suits picking the fastest of several mirror servers.

CombinatorSettles when
Promise.allAll succeed, or the first failure
Promise.allSettledEverything finished; never rejects
Promise.raceThe first one to settle, either way
Promise.anyThe first success
Mental model: start, wait, value or throw
  1. Calling starts the work, gives a Promise
  2. await pauses only this function
  3. The event loop keeps serving others
  4. Fulfilled -> value; rejected -> throw

Start everything first and then wait, and the work runs concurrently; start-wait-start-wait runs it in line.

General pattern

javascript
async function name(input) {
  try {
    const one = await stepThatReturnsAPromise(input);   // in sequence
    const [a, b] = await Promise.all([taskA(one), taskB(one)]); // together
    return combine(a, b);
  } catch (error) {
    throw new Error('What failed, in plain words', { cause: error });
  }
}

const result = await name(value);   // top-level await: ES modules only

Steps that depend on each other are awaited in sequence; independent tasks run together under Promise.all. The catch rethrows with a clear message and keeps the original error as the cause.

Example: reading two config files concurrently

The example writes app.json and messages.json into a temporary folder, then loadConfig() reads both at once with Promise.all. It first calls loadConfig() without await to show that a Promise comes back, then awaits the real result. Finally it points loadConfig() at a folder that does not exist and prints the error message plus the original error's code (ENOENT) from its cause.

load-config.mjs
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';

const dir = await mkdtemp(path.join(tmpdir(), 'config-'));
await writeFile(path.join(dir, 'app.json'), '{"name":"Tutorial API","port":3000}');
await writeFile(path.join(dir, 'messages.json'), '{"welcome":"Mingalaba"}');

async function loadConfig(folder) {
  try {
    const [app, messages] = await Promise.all([
      readFile(path.join(folder, 'app.json'), 'utf8'),
      readFile(path.join(folder, 'messages.json'), 'utf8'),
    ]);
    return { app: JSON.parse(app), messages: JSON.parse(messages) };
  } catch (error) {
    throw new Error('Could not load configuration', { cause: error });
  }
}

const pending = loadConfig(dir);
console.log('loadConfig returned:', pending instanceof Promise ? 'a Promise' : 'data');

const config = await pending;
console.log(config.app.name, '-', config.messages.welcome);

try {
  await loadConfig(path.join(dir, 'missing'));
} catch (error) {
  console.log(error.message, '| cause:', error.cause.code);
}

await rm(dir, { recursive: true, force: true });

Code breakdown

  1. Two reads at onceconst [app, messages] = await Promise.all([

    Both readFile calls start immediately inside the array, and Promise.all returns their results in input order once both finish, so destructuring can name them.

  2. Wrapping the errorthrow new Error('Could not load configuration', { cause: error });

    It throws a message that makes sense to the caller while keeping the original error, such as ENOENT, in cause, so no detail is lost when debugging.

  3. Calling without awaitconst pending = loadConfig(dir);

    Calling an async function without await starts the work but hands back a Promise, not data: the root of the bug in the problem section.

  4. Waiting for the resultconst config = await pending;

    An already-started Promise can be awaited later. That is the essence of concurrency: start first, wait later.

  5. Catching the failureconsole.log(error.message, '| cause:', error.cause.code);

    The missing folder makes readFile reject, await throws, and try/catch catches it; cause.code reveals ENOENT (no such file).

You should see
loadConfig returned: a Promise
Tutorial API - Mingalaba
Could not load configuration | cause: ENOENT

Sequential versus concurrent

The code below runs task A (60 ms) and task B (20 ms) two ways. Sequentially, B starts only after A, so it takes about 80 ms in total and "done" prints A then B. With Promise.all both start together, it takes about 60 ms and B finishes first, yet the result array is still ['A', 'B'], in input order.

order.mjs
import { setTimeout as sleep } from 'node:timers/promises';

async function task(name, ms) {
  await sleep(ms);
  console.log('done:', name);
  return name;
}

console.log('-- sequential');
await task('A', 60);
await task('B', 20);

console.log('-- concurrent');
console.log(await Promise.all([task('A', 60), task('B', 20)]));

An unhandled rejection stops the process

Since Node 15, a rejected Promise that nobody catches makes Node print the error and exit with code 1. Handle every Promise with await inside try/catch, or with .catch().

In real projects

Where this shows up in real projects

An Express route handler typically does I/O: load the user from the database, load their orders, call a recommendation service. Running the two lookups that only need the user ID together with Promise.all often cuts the response time roughly in half. Because Express 5 forwards a rejected async handler to the error middleware, a database outage produces a 500 response instead of a hanging request.

On a dashboard that pulls ten widgets from different services, Promise.allSettled shines: when one service is down you still show the other nine and display "temporarily unavailable" only in the broken widget. Putting a timeout on every external API call is standard practice too; with fetch() you can pass signal: AbortSignal.timeout(2000).

Common mistakes

Common mistakes

1. Using await inside forEach

files.forEach(async (f) => { await upload(f); }) does not wait for the Promises its callback returns, so "All uploaded" prints before the uploads finish and their errors go uncaught. Use await inside for...of to go one by one, or await Promise.all(files.map(upload)) to go concurrently.

2. Expecting try/catch to catch a Promise you did not await

With try { saveUser(data); } catch {}, the rejection happens after the try block has already finished, so the catch never runs and you get an unhandled rejection. Put await inside the try.

3. Promise.all over a huge list

Calling Promise.all(urls.map(fetch)) on ten thousand URLs opens ten thousand connections at once and overwhelms your server or the remote API. Process the list in small batches, for example ten at a time.

Mini challenge

Mini challenge: a dashboard loader with timeouts

Call three services concurrently, give each a 100 ms timeout, and report every outcome with Promise.allSettled.

  • fetchService(name, ms, shouldFail) waits ms using timers/promises' setTimeout, then returns a string or throws
  • withTimeout(promise, ms, label) rejects with a timeout error via Promise.race and clears its timer
  • Run users (20 ms), orders (30 ms, fails) and reports (300 ms) with Promise.allSettled
  • Print each outcome as OK or FAIL, in input order
dashboard.mjs
import { setTimeout as sleep } from 'node:timers/promises';

async function fetchService(name, ms, shouldFail = false) {
  // TODO: wait ms, then throw "<name> failed" or return "<name> ok"
}

function withTimeout(promise, ms, label) {
  // TODO: race the promise against a timer that rejects with
  //       "<label> timed out after <ms> ms"; clear the timer afterwards
}

// TODO: Promise.allSettled over users (20), orders (30, fails), reports (300)
// TODO: print "OK   <value>" or "FAIL <reason.message>" for each result

Expected: Expected output: OK users ok FAIL orders failed FAIL reports timed out after 100 ms

Show hint

Build the timer with new Promise((_, reject) => { timer = setTimeout(...) }) and return Promise.race([promise, timeout]).finally(() => clearTimeout(timer)). Each allSettled result has status plus value or reason.

Show solution
dashboard.mjs
import { setTimeout as sleep } from 'node:timers/promises';

async function fetchService(name, ms, shouldFail = false) {
  await sleep(ms);
  if (shouldFail) throw new Error(`${name} failed`);
  return `${name} ok`;
}

function withTimeout(promise, ms, label) {
  let timer;
  const timeout = new Promise((_, reject) => {
    timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms} ms`)), ms);
  });
  return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}

const results = await Promise.allSettled([
  withTimeout(fetchService('users', 20), 100, 'users'),
  withTimeout(fetchService('orders', 30, true), 100, 'orders'),
  withTimeout(fetchService('reports', 300), 100, 'reports'),
]);

for (const result of results) {
  if (result.status === 'fulfilled') console.log('OK  ', result.value);
  else console.log('FAIL', result.reason.message);
}

Quick quiz 1 / 3

Given async function getAge() { return 30; }, what does console.log(getAge()) print?

Quick quiz 2 / 3

In Promise.all([a(), b(), c()]), b() rejects. What happens?

Quick quiz 3 / 3

getUser() provides the id; getOrders(id) and getReviews(id) need only that id. Which is correct and fastest?

What to remember

  • A Promise moves from pending to fulfilled or rejected exactly once.
  • An async function always returns a Promise; await pauses only that function, never the event loop.
  • Start independent work first and wait with Promise.all; use allSettled when you need every outcome.
  • Catch rejections with try/catch and keep the original error with { cause }.

Discover Promises in Node.js — Node.js

Asynchronous work — Node.js

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Asynchronous Node.js with Promises and async/await | Thuta Learning