Skip to content
jshacks.dev
Async

Promise.withResolvers: Deferreds Without the Boilerplate

Learn how Promise.withResolvers returns a promise with its resolve and reject functions, replaces the deferred boilerplate and where it fits in real code.

7 min read
Summarize in AI
Flat illustration of jobs on a conveyor heading to a rack of workers, with the JavaScript, Node.js, Redis, RabbitMQ and Apache Kafka logos.

For years, code that needed to settle a promise from outside its constructor started with the same five lines: declare two variables, create the promise, assign the variables inside the executor, then use them somewhere else. Promise.withResolvers() replaces that with one call that returns an object holding the promise and both functions. It is a small method with a clear purpose, and it arrived in ES2024, so it is available in Node.js 22 and later and in current browsers. This post shows the old pattern and the new one with printed output, walks through four uses where a deferred is genuinely the right tool, covers the TypeScript setup and lists the cases where you should not reach for it, because most promises do not need to be settled from outside.

The old pattern

JavaScript
let resolve;
let reject;

const promise = new Promise((res, rej) => {
  resolve = res;
  reject = rej;
});

setTimeout(() => resolve("done"), 10);

console.log(await promise);
Text
done

It works, and it has two problems. It leaks two mutable variables into the surrounding scope, and in TypeScript those variables are typed as possibly unassigned, so you need definite-assignment assertions or non-null casts. Every codebase ended up with its own defer() helper to hide it.

The new pattern

JavaScript
const { promise, resolve, reject } = Promise.withResolvers();

setTimeout(() => resolve("done"), 10);

console.log(await promise);
Text
done

The return value is a plain object with three properties. The functions work exactly as in an executor: the first call to resolve or reject settles the promise, and later calls do nothing.

JavaScript
const { promise, resolve, reject } = Promise.withResolvers();

resolve("first");
resolve("second");
reject(new Error("ignored"));

console.log(await promise);
console.log(typeof resolve, typeof reject);
Text
first
function function

Why a deferred exists at all

Most promises are created around an operation that knows when it finishes. The executor starts the work, and its callbacks call resolve. But sometimes the code that creates the promise is not the code that knows the answer. A request is sent in one place and the response is matched elsewhere. A component asks for a value that another event provides. That separation is what a deferred is for.

Use 1: matching responses to requests

Over a socket or a message channel, replies arrive as events, not as return values. A map of pending deferreds turns the protocol into promises.

JavaScript
const pending = new Map();
let nextId = 1;

function request(payload) {
  const id = nextId++;
  const { promise, resolve } = Promise.withResolvers();
  pending.set(id, resolve);
  return { id, promise, payload };
}

function onMessage(message) {
  const resolve = pending.get(message.id);
  if (resolve) {
    pending.delete(message.id);
    resolve(message.result);
  }
}

const first = request("ping");
const second = request("time");

onMessage({ id: 2, result: "12:00" });
onMessage({ id: 1, result: "pong" });

console.log(await first.promise, await second.promise);
Text
pong 12:00

The replies arrived in the opposite order of the requests, and each promise still received its own answer. That is the whole point: the caller awaits a promise while a different part of the program settles it.

Use 2: waiting for an event once

A small gate that opens when something happens.

JavaScript
import { EventEmitter } from "node:events";

const bus = new EventEmitter();
const { promise: ready, resolve: markReady } = Promise.withResolvers();

bus.once("ready", markReady);

async function start() {
  console.log("waiting for ready");
  await ready;
  console.log("ready seen, continuing");
}

const running = start();
bus.emit("ready");
await running;
Text
waiting for ready
ready seen, continuing

Any number of callers can await ready, and all continue when it resolves. For waiting on a single event, events.once(bus, "ready") is a ready-made alternative, but a deferred lets several unrelated pieces of code share one gate.

Use 3: a queue that hands out work

An async queue where consumers wait for items that producers add later.

JavaScript
class AsyncQueue {
  #items = [];
  #waiters = [];

  push(item) {
    const waiter = this.#waiters.shift();
    if (waiter) waiter.resolve(item);
    else this.#items.push(item);
  }

  pull() {
    if (this.#items.length > 0) return Promise.resolve(this.#items.shift());
    const deferred = Promise.withResolvers();
    this.#waiters.push(deferred);
    return deferred.promise;
  }
}

const queue = new AsyncQueue();

const consumer = queue.pull().then((item) => console.log("got", item));
queue.push("job-1");
await consumer;

queue.push("job-2");
console.log("then got", await queue.pull());
Text
got job-1
then got job-2

When a consumer arrives first, it waits on a deferred, and when a producer arrives first, the item waits in the array. The deferred is the bridge between the two timings, and writing it without withResolvers needs the old boilerplate inside pull.

Use 4: settling from a timeout or abort

A deferred can be settled from several places, with the first one winning.

JavaScript
function waitForFlag(timeoutMs) {
  const { promise, resolve, reject } = Promise.withResolvers();

  const timer = setTimeout(() => reject(new Error("flag never set")), timeoutMs);

  return {
    promise: promise.finally(() => clearTimeout(timer)),
    set: () => resolve("flag set"),
  };
}

const quick = waitForFlag(50);
quick.set();
console.log(await quick.promise);

const never = waitForFlag(20);

try {
  await never.promise;
} catch (error) {
  console.log(error.message);
}
Text
flag set
flag never set

The first call settled through set, the second through the timer. Because settling is idempotent, neither path needs to check whether the other already ran.

TypeScript

With lib set to ES2024 or later, the method is typed, and the three properties are non-optional, so no assertions are needed.

TypeScript
const { promise, resolve, reject } = Promise.withResolvers<number>();

resolve(42); // resolve is (value: number | PromiseLike<number>) => void
const value: number = await promise;

For older libraries, a one-line polyfill is enough.

JavaScript
if (!Promise.withResolvers) {
  Promise.withResolvers = function withResolvers() {
    let resolve;
    let reject;
    const promise = new this((res, rej) => {
      resolve = res;
      reject = rej;
    });
    return { promise, resolve, reject };
  };
}

The this makes it work for subclasses, matching the specification.

When not to use it

A deferred hides control flow. The code that settles the promise can be far from the code that awaits it, and if nothing ever calls resolve, the awaiting code hangs forever with no error. Prefer the normal constructor when the same function starts the work and handles the callback.

JavaScript
// no deferred needed
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

And never leave a path where the deferred is neither resolved nor rejected: timeouts, error branches and shutdown should all settle pending deferreds so awaiting callers are released.

Keeping deferreds under control

A deferred is a loose end by design. The promise exists, somebody is waiting on it and the code that will settle it lives elsewhere, so the usual guarantee that the executor finishes is gone. The practical risk is a promise that never settles, which shows up as a request that hangs, a shutdown that never completes or a test that times out with no clue why.

Three habits reduce that risk. First, keep the deferred and its settling code close together, ideally in one small class or function, so a reader can see every path that resolves or rejects it. Second, attach a timeout or an abort signal to anything a user is waiting on, and make the timeout reject the deferred. Third, on shutdown, reject or resolve every pending deferred explicitly, so awaiting callers are released with a clear error and not left hanging until the process is killed.

It also helps to store deferreds in a structure with an obvious lifecycle, such as a map keyed by request id, and to remove an entry as soon as it settles. A map that grows without bound is a memory leak with a very readable cause. In tests, you can use a deferred to control timing exactly: start an operation, assert on the intermediate state and then resolve it on your terms, which is far more reliable than sleeping for a guessed number of milliseconds.

Testing code that uses deferreds

Deferred promises are valuable in tests as well as in code, because they let a test control the exact moment an operation completes. To test a component that waits for a reply, create a deferred, hand its promise to the stub, assert the in-between state, such as a loading indicator, and then call resolve and assert the final state. To test failure handling, call reject instead. For code that stores deferreds, such as a request and reply matcher, write tests for the cases that leak: a reply that never arrives should be released by a timeout, a duplicate reply should be ignored and shutdown should settle every pending entry. After each test, assert that the internal map of pending entries is empty. A leftover entry is the signature of a promise that will never settle, and catching it in a test is far cheaper than finding it as a hung request in production.

Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.