Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 133 ยท Asynchronous Programming

Promises in Depth

Learn Node.js promises in depth - states, chaining, microtask timing, Promise.all, allSettled, race, any, withResolvers, unhandled rejections and promise-based core APIs.

A promise is an object that stands for a value you do not have yet. It starts out waiting, and later either succeeds with a value or fails with a reason. You can attach handlers to it before, during or after that moment, and they will run correctly in every case. That one idea removes most of the pain of callbacks: errors travel along a chain, steps read top to bottom, and several operations can be combined with a single call.

async/await, which you will meet in the next lesson, is built directly on promises, so a firm grip on them pays off everywhere. Here we go beyond the basics: the three states, how chaining really works, exactly when handlers run, the five combinators, unhandled rejections (a real way to crash a Node process), and the promise-based APIs in Node's own modules.

Creating and consuming a promise

You create a promise with new Promise(executor). The executor is a function that runs immediately and receives two functions: resolve(value) to succeed and reject(error) to fail. A promise can be settled only once; later calls to resolve or reject are silently ignored.

Node.js A promise and its three states

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The three states are pending (not decided yet), fulfilled (has a value) and rejected (has a reason, ideally an Error). Once fulfilled or rejected, a promise is settled and never changes again. Promise.resolve(value) and Promise.reject(error) are shortcuts for creating already-settled promises.

Reject with Error objects, not strings. An Error carries a stack trace and a name; a bare string carries nothing, which makes failures much harder to debug.

Chaining

promise.then(onFulfilled, onRejected) returns a new promise. That new promise is settled by whatever the handler does:

  • If the handler returns a value, the new promise fulfills with it.
  • If the handler returns a promise, the new promise follows that promise (it "adopts" its state).
  • If the handler throws, the new promise rejects with the thrown error.

.catch(fn) is shorthand for .then(undefined, fn), and .finally(fn) runs on both outcomes without changing the value (it only changes the result if it throws).

Node.js Values, promises and errors flowing down a chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Study the shape: a rejection skips every .then until it reaches a .catch, which can recover by returning a value. After that the chain is healthy again. This is the promise version of try/catch.

A classic mistake: nesting instead of chaining

If you start a new .then inside a .then without returning it, the outer chain does not wait for it, and its errors are lost.

Node.js Forgetting to return inside then

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The wrong chain resolves with undefined immediately, and its inner message appears later, out of order. The fix is always the same: return the inner promise.

When handlers run: microtasks

Handlers passed to then, catch and finally never run synchronously, even if the promise is already settled. They are queued as microtasks, which Node drains after the current piece of synchronous code finishes and before it returns to the event loop's timers and I/O (the details are in The Event Loop). That is why promise callbacks beat setTimeout(fn, 0) and setImmediate.

Node.js Ordering: sync, nextTick, microtasks, timers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The numbers show the order. Synchronous code first (1, 2), then the promise microtasks in the order they were queued (3, 4), then the process.nextTick callback (5), then the timer and setImmediate (6 and 7, in either order). Two details are worth knowing. In a CommonJS script the nextTick queue is drained before promise microtasks, so there 5 would come first; in an ES module the module body itself runs inside a promise job, so microtasks go first. And the order of setTimeout(fn, 0) and setImmediate from the main module is not guaranteed in general; do not build logic on it. The practical rule is simple: a then handler runs after the current function finishes, never in the middle of it.

Combinators

Four static methods combine many promises into one. They all accept any iterable and treat non-promise values as already fulfilled.

Method Fulfills when Rejects when
Promise.all all fulfill (array of values, same order) the first one rejects
Promise.allSettled all settle (array of outcome objects) never
Promise.race the first one settles with a value the first one settles with an error
Promise.any the first one fulfills all reject (AggregateError)
Node.js all, allSettled, race and any

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Choosing between them:

  • all when you need every result and one failure should abort the whole job (loading all data a page needs). Note that the other promises keep running; all does not cancel them, it just stops waiting.
  • allSettled when failures are acceptable and you want a report (send 50 emails, collect which failed).
  • race for timeouts: race the real work against a timer. Prefer AbortSignal.timeout, shown in AbortController and Cancellation, because a lost race leaves the slow operation running.
  • any for redundancy: ask three mirrors, take the first good answer. If all fail you get an AggregateError with an errors array.

An empty array is a special case: Promise.all([]) fulfills with [], but Promise.any([]) rejects, and Promise.race([]) stays pending forever.

Promise.withResolvers

Sometimes the code that creates a promise is not the code that settles it, for example when you wrap an event. Promise.withResolvers() (available in Node 22 and later) returns the promise together with its two functions, so you do not need the executor dance with a variable declared outside.

Node.js Promise.withResolvers for event wrappers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

(For this exact task Node already offers events.once(emitter, name), which returns a promise; the example is just the smallest honest use of withResolvers.)

Unhandled rejections

If a promise is rejected and nothing ever attaches a handler, Node considers it an unhandled rejection. Since Node 15 the default is to treat it like an uncaught exception: print the error and exit with code 1. This is a feature. A forgotten await or missing .catch otherwise hides failures forever.

Node.js A rejection nobody handles (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first line prints, then Node prints the error (Error: config.json is missing, with a stack trace whose first line points at loadConfig in main.mjs:2:9) and exits with code 1, because the rejection had no handler. The fix is to await the call inside a try/catch, or to end the chain with .catch.

You can observe such rejections globally with process.on('unhandledRejection', (reason, promise) => ...). Use that for logging and a clean shutdown, not to keep running as if nothing happened. A promise that gets its handler late triggers 'rejectionHandled', and that is a smell: attach handlers in the same tick you create the promise.

Error handling patterns

Node.js Wrapping errors with cause

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Throwing inside then/async code converts to a rejection, so a single catch handles both your own errors and unexpected ones such as a SyntaxError from JSON.parse. Wrap lower-level errors with { cause: err } so the original stays available for debugging while callers see a meaningful error type.

Promise-based APIs in Node

Modern Node ships promise versions of its callback APIs, usually under a /promises path or with a .promises property. Prefer them; there is nothing to wrap.

NODE
import { readFile, writeFile } from 'node:fs/promises';
import { setTimeout as sleep } from 'node:timers/promises';
import { pipeline } from 'node:stream/promises';
import { once } from 'node:events';
import { scrypt } from 'node:crypto'; // callback API: promisify it yourself
Node.js fs/promises and timers/promises together

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

A promise can only ever produce one result. For things that happen repeatedly (every chunk of a stream, every request to a server) use events, streams, or async iterators (see Async Iterators and Generators).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens if resolve() is called twice inside the same promise executor?

    A promise settles once. After it is fulfilled or rejected, further resolve or reject calls have no effect.
  2. 2. What does .then(() => { somePromise(); }) do with the inner promise?

    The handler returns undefined, so the chain continues immediately. Return the inner promise (or use async/await) to make the chain wait for it.
  3. 3. Which combinator gives you a result for every input, whether it succeeded or failed, and never rejects?

    allSettled waits for every promise and returns an array of objects with status fulfilled or rejected.
  4. 4. In what order do these run - setTimeout(fn, 0), Promise.resolve().then(fn), and code written after them in the same script?

    Synchronous code finishes first, then the microtask queue (promise handlers) is drained, and only then does the event loop reach timers.
  5. 5. What does Node do by default with a rejected promise that has no handler?

    Since Node 15 an unhandled rejection raises an uncaught exception, which crashes the process unless you handle it.

Summary

  • A promise is pending, then fulfilled or rejected exactly once.
  • then returns a new promise: returned values pass on, returned promises are followed, thrown errors reject.
  • A catch recovers; finally runs either way and passes the value through.
  • Handlers run as microtasks: after the current synchronous code, before timers.
  • all fails fast, allSettled reports everything, race takes the first outcome, any takes the first success.
  • Promise.withResolvers() creates a promise plus its resolve and reject functions.
  • Unhandled rejections crash the process by design; always await or catch.
  • Prefer the built-in promise APIs (fs/promises, timers/promises, stream/promises).

Next: async/await Patterns