Skip to content
jshacks.dev
Async

How to Await Events in Order With Promise.withResolvers

Await events in order with Promise.withResolvers: build a message awaiter, a request-reply correlator and a latch, with timeouts and cleanup.

7 min read
Summarize in AI
Flat illustration of one event fanning out to several listeners, with the JavaScript, Redis and Socket.io logos.

Some code needs to pause until something specific happens elsewhere: the reply to a request sent over a socket, the third message in a conversation, a signal that setup has finished. The thing it waits for arrives through a different path than the code that waits. Promise.withResolvers() is built for that gap. It creates a promise and hands back its resolve and reject, so the waiting code can hold the promise while the event handler holds the resolver. This post goes beyond the one-event case covered in wrapping an event with Promise.withResolvers and shows how to await events that arrive over time and in sequence: a queue of awaiters for incoming messages, a request and reply correlator keyed by an id, and a latch that releases many waiters at once. It uses Node.js 24, where the method is available, and includes timeouts and cleanup, since a waiter that is never released is a leak.

An awaitable message queue

Messages arrive on a handler, and consumers want await next(). Two lists keep this straight: messages that arrived before anyone asked, and waiters that asked before any message arrived. A push serves a waiter if there is one, otherwise stores the message. A next takes a stored message if there is one, otherwise creates a waiter.

inbox.jsJavaScript
export class Inbox {
  #messages = [];
  #waiters = [];

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

  next() {
    if (this.#messages.length > 0) return Promise.resolve(this.#messages.shift());
    const waiter = Promise.withResolvers();
    this.#waiters.push(waiter);
    return waiter.promise;
  }

  close(reason = new Error("inbox closed")) {
    for (const waiter of this.#waiters.splice(0)) waiter.reject(reason);
  }
}

const inbox = new Inbox();
inbox.push("early");

setTimeout(() => inbox.push("late"), 10);

console.log(await inbox.next());
console.log(await inbox.next());
Text
early
late

The first next() found a stored message and returned it. The second had to wait, and the later push resolved it. The close method is the part that is easy to forget: when the source goes away, every pending waiter must be rejected, or the code awaiting them hangs for good.

Request and reply over one channel

A common protocol sends a request with an id over a single connection and receives replies on the same connection, in any order. A map from id to resolver connects each reply to the code that asked.

rpc.jsJavaScript
export class RpcClient {
  #pending = new Map();
  #nextId = 1;

  constructor(send) {
    this.send = send;
  }

  call(method, params) {
    const id = this.#nextId++;
    const { promise, resolve, reject } = Promise.withResolvers();
    this.#pending.set(id, { resolve, reject });
    this.send({ id, method, params });
    return promise;
  }

  // called by the connection when a reply arrives
  receive({ id, result, error }) {
    const waiter = this.#pending.get(id);
    if (!waiter) return; // late or unknown reply
    this.#pending.delete(id);
    if (error) waiter.reject(new Error(error));
    else waiter.resolve(result);
  }

  closeAll(reason) {
    for (const waiter of this.#pending.values()) waiter.reject(reason);
    this.#pending.clear();
  }
}

// A fake server that answers in reverse order
const outbox = [];
const client = new RpcClient((message) => outbox.push(message));

const a = client.call("add", [1, 2]);
const b = client.call("add", [10, 20]);

for (const { id, params } of outbox.reverse()) {
  client.receive({ id, result: params[0] + params[1] });
}

console.log(await a, await b);
Text
3 30

The server replied to the second request first, and each caller still received its own answer, because the id picks the right resolver. The map is the whole trick, and the cleanup matters: delete the entry on reply so the map does not grow, and reject everything left when the connection closes.

Add a timeout per request

A reply that never comes leaves its caller waiting and its entry in the map. Give each call a deadline that rejects the promise and removes the entry.

rpc-timeout.jsJavaScript
export class RpcClient {
  #pending = new Map();
  #nextId = 1;

  constructor(send, { timeoutMs = 1000 } = {}) {
    this.send = send;
    this.timeoutMs = timeoutMs;
  }

  call(method, params) {
    const id = this.#nextId++;
    const { promise, resolve, reject } = Promise.withResolvers();

    const timer = setTimeout(() => {
      this.#pending.delete(id);
      reject(new Error(`${method} timed out after ${this.timeoutMs} ms`));
    }, this.timeoutMs);

    this.#pending.set(id, {
      resolve: (value) => {
        clearTimeout(timer);
        resolve(value);
      },
      reject: (error) => {
        clearTimeout(timer);
        reject(error);
      },
    });

    this.send({ id, method, params });
    return promise;
  }

  receive({ id, result, error }) {
    const waiter = this.#pending.get(id);
    if (!waiter) return;
    this.#pending.delete(id);
    if (error) waiter.reject(new Error(error));
    else waiter.resolve(result);
  }
}

const client = new RpcClient(() => {}, { timeoutMs: 20 });
try {
  await client.call("slowMethod", []);
} catch (error) {
  console.log(error.message);
}
Text
slowMethod timed out after 20 ms

Both settle paths clear the timer, so a reply that arrives in time does not leave a timer running. A reply that arrives after the timeout finds no entry and is ignored, which is why receive checks for the missing waiter.

A latch for many waiters

Sometimes many pieces of code wait for the same one-time event, such as "the application has finished starting". A single deferred serves them all, since any number of callers can await the same promise.

latch.jsJavaScript
export function createLatch() {
  const { promise, resolve } = Promise.withResolvers();
  let open = false;
  return {
    wait: () => promise,
    release: () => {
      open = true;
      resolve();
    },
    get isOpen() {
      return open;
    },
  };
}

const ready = createLatch();
const order = [];

const waiters = [1, 2, 3].map(async (n) => {
  await ready.wait();
  order.push(`worker ${n} started`);
});

order.push("releasing");
ready.release();
await Promise.all(waiters);
console.log(order);
Text
[ 'releasing', 'worker 1 started', 'worker 2 started', 'worker 3 started' ]

All three workers were blocked until release, then continued in the order they began waiting. A caller that arrives after the latch has opened gets an already-resolved promise and continues at once, which is the behavior you want for a startup gate.

Mistakes to avoid

Waiters that never end. Every awaited event needs a path where it does not arrive: a timeout, a close handler or an abort signal. Count your waiters in tests and assert that the number returns to zero.

Resolving the wrong waiter. With sequential messages, make sure the order of waiters matches the order of messages. A first-in first-out list does that. With correlated replies, use an id and never rely on arrival order.

Forgetting duplicates. A reply that arrives twice, or after a timeout, must not throw. Check for the missing entry, as in receive.

Why a deferred and not an executor

The executor form of new Promise forces the code that will settle the promise to live inside the callback. That works when the event source is created right there, and it fails here, because the code that waits and the code that settles are in different methods that share only an object. A deferred stored in a field or a map is the natural fit. The cost is responsibility: an executor settles automatically if it throws, while a stored deferred has no such safety net, so every path that creates one must also have a path that settles it. The three classes above each carry that responsibility explicitly, with close, closeAll, a timeout and release.

A useful discipline is to store only resolve and reject and never the promise itself in the pending list, since the promise has already been handed to the caller. Keeping a second reference to it invites code that awaits it from the wrong place. The same discipline makes the structure easy to inspect: the size of the pending list is the number of callers currently blocked, which is a number worth exporting as a metric.

Ordering guarantees

First-in first-out matching only holds if there is one consumer loop. If two parts of the code both call next(), they receive messages in the order they asked, which is well defined, but neither knows what the other consumed, so a protocol that expects one specific message next can receive the wrong one. For protocols with a strict sequence, use a single reader that parses messages and dispatches them, and let other code subscribe to typed events from it. For protocols where messages are independent, such as job results, many consumers sharing an inbox is exactly what you want, because each message goes to exactly one of them.

Cancelling a waiter

Waiters need to be cancelable. A caller that gave up should not receive a message later and swallow it. Give next an optional AbortSignal: when it aborts, remove that waiter from the list and reject its promise with the signal's reason. Without the removal, the next message would be delivered to a promise nobody is listening to, and it would be lost, which shows up as a message that was sent and never processed. Removing the waiter by identity from the list is a small linear search, which is fine for the short lists these structures hold.

Testing the structures

All three classes are deterministic, so tests need no timers except for the timeout case. For the inbox, test both orders: push before next and next before push, plus several waiters and several messages interleaved. For the correlator, reply in reverse order and in a shuffled order, send a reply for an unknown id and assert that nothing throws, and call closeAll and assert that every pending call rejects. For the timeout, use fake timers and tick past the deadline. For the latch, add waiters before and after release and assert that both continue. These tests are short, and together they cover the failures that make this kind of code a source of hangs 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.