agyanadda@gmail.com

Node.js Promises and async/await

Asynchronous Programming 1 min read Updated Dec 3, 2026 Topic 13 of 30

A Promise represents a value that will be ready later. It is pending, then fulfilled (success) or rejected (error).

async / await

  • Mark a function async and it always returns a Promise
  • Inside it, await promise pauses that function (not the whole server) until the result is ready
  • Handle errors with try / catch

Running tasks in parallel

Awaiting one by one is slow when tasks don't depend on each other:

  • Promise.all([...]) — run together, fail if any fails
  • Promise.allSettled([...]) — wait for all and report each result
  • Promise.race([...]) / Promise.any([...]) — the first to finish / succeed

Creating a promise

new Promise((resolve, reject) => { ... }) — useful for wrapping old APIs. For delays, node:timers/promises has setTimeout that returns a promise.

Top-level await

In ES modules you can use await directly at the top of a file.

Example

Example — Sequential vs parallel JavaScript
import { setTimeout as wait } from 'node:timers/promises';

async function fetchUser(id) {
  await wait(500);                 // pretend this is a database call
  if (id === 0) throw new Error('User not found');
  return { id, name: `User ${id}` };
}

console.time('sequential');
const a = await fetchUser(1);
const b = await fetchUser(2);
console.timeEnd('sequential');       // ~1000 ms

console.time('parallel');
const [c, d] = await Promise.all([fetchUser(3), fetchUser(4)]);
console.timeEnd('parallel');         // ~500 ms

const results = await Promise.allSettled([fetchUser(5), fetchUser(0)]);
results.forEach((r) => console.log(r.status, r.value?.name ?? r.reason.message));
// fulfilled User 5
// rejected User not found

try {
  await fetchUser(0);
} catch (err) {
  console.error('Caught:', err.message);
}

The parallel version takes about half the time. allSettled reports each result even when one fails, and try/catch handles the error from fetchUser(0).

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which runs promises together and fails if any one fails?

Exercise 2 True / False

await blocks the entire Node.js server until the promise finishes.

Exercise 3 Fill in the Blank

Handle errors from await with try / ___

Frequently Asked Questions

You get a pending Promise instead of the value, and errors from it may become unhandled rejections, which can crash Node. Linters such as ESLint can warn about floating promises.