brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Promise.withResolvers() gives you resolve and reject outside the promise

Web-Development
~/tips/tip-javascript-promise-withresolvers

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

Creates a promise and hands you its resolve and reject functions to call later.

Sometimes a promise has to be settled by something that happens later, somewhere else in your code: a message on a WebSocket, an event from a stream. The old way was to declare let resolve, reject, then copy them out of the executor of new Promise(). It always felt like a hack to me. Promise.withResolvers() is the official version of that hack.

It returns a plain object with three things: the promise and the two functions that settle it.

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

MDN says it’s exactly the same as the old pattern, only shorter and without the let. Where it pays off is code like this, where you send a request over a WebSocket and wait for the answer with the same id:

const pending = new Map();

function ask(socket, id, payload) {
  const { promise, resolve, reject } = Promise.withResolvers();
  pending.set(id, { resolve, reject });
  socket.send(JSON.stringify({ id, payload }));
  return promise;
}

socket.addEventListener("message", (event) => {
  const msg = JSON.parse(event.data);
  pending.get(msg.id)?.resolve(msg.result);
  pending.delete(msg.id);
});

The caller just writes const result = await ask(socket, 7, "status") and doesn’t care how the answer arrives. Without withResolvers() you’d wrap the whole thing in an executor and the nesting grows fast.

The catch is the same as with the old trick, only easier to miss. A promise that nobody resolves stays pending forever, and an await on it never returns. If the socket closes, walk through pending and call reject() on everything in it, or race the promise against a timeout. My advice is to write that cleanup at the same moment you write the Map.

Browser support: Chrome and Edge 119, Firefox 121 and Safari 17.4, so it’s Baseline widely available on MDN since September 2026.

Further reading: MDN: Promise.withResolvers()

More Web-Development tips ab -n 200 -c 10 https://example.com/ console.assert(items.length > 0, 'cart is empty', items) document.designMode = "on" function save(item) { Save draft All Web-Development tips (67) All topics

Link