How to Use Promise.withResolvers to Wrap an Event
Use Promise.withResolvers to wrap an event in a promise without the executor nesting: one-shot events, timeouts, reusable deferreds and the older fallback.

Wrapping an event in a promise has always meant nesting. You write new Promise((resolve, reject) => { ... }), and everything that touches resolve has to live inside that callback, even when the code that settles it is far away. Promise.withResolvers() removes the nesting. It returns an object with a promise and the resolve and reject functions that control it, so you can create the promise in one place and settle it in another. The method is part of ES2024, and it is available in Node.js 22 and later and in current Chrome, Firefox and Safari. This post shows how to use Promise.withResolvers to wrap an event, how to add a timeout and cleanup, how to build a reusable deferred value, and what to write for runtimes that lack it. For the older callback form, see turning a callback API into a promise.
The shape of the API
Promise.withResolvers() takes no arguments and returns three things. You usually destructure them.
const { promise, resolve, reject } = Promise.withResolvers();
setTimeout(() => resolve("settled from outside"), 10);
console.log(await promise);settled from outsideThe promise and its controls are separate values, so resolve can be handed to an event listener, stored on an object or returned from a function. The same thing was possible before with a variable declared outside the executor and assigned inside, a pattern people called a deferred. The new method makes that pattern one line and removes the awkward let resolve; declarations.
Wrap a one-shot event
The common case is a promise that settles when an event fires once. Create the deferred, register the listener to call resolve, and return the promise.
export function waitForEvent(target, name) {
const { promise, resolve } = Promise.withResolvers();
target.addEventListener(name, resolve, { once: true });
return promise;
}
const target = new EventTarget();
setTimeout(() => target.dispatchEvent(new Event("loaded")), 10);
const event = await waitForEvent(target, "loaded");
console.log(event.type);loadedThe listener passes the event object straight to resolve, and { once: true } removes it after the first call, so nothing leaks. Compared with the executor form, the code reads in the order it happens: create, listen, return. The executor form says the same in three levels of indentation.
Reject on an error event
Many event sources have a success event and a failure event. Settle the promise from whichever fires first, and remove both listeners afterward so the loser does not linger.
export function loadImage(url) {
const { promise, resolve, reject } = Promise.withResolvers();
const image = new Image();
const cleanup = () => {
image.removeEventListener("load", onLoad);
image.removeEventListener("error", onError);
};
const onLoad = () => {
cleanup();
resolve(image);
};
const onError = () => {
cleanup();
reject(new Error(`could not load ${url}`));
};
image.addEventListener("load", onLoad);
image.addEventListener("error", onError);
image.src = url;
return promise;
}
try {
const image = await loadImage("/missing.png");
console.log(image.width);
} catch (error) {
console.log(error.message);
}could not load /missing.pngThe sample assumes a browser, where Image exists, and a missing file. The cleanup function matters because a promise can settle only once, but listeners stay attached until they are removed, and an image element reused for another load would call a stale handler.
Add a timeout
A promise that waits for an event needs a deadline, or a missed event hangs the caller. The deferred makes a timeout easy to add, because the timer can call reject directly.
export function waitForEventWithTimeout(target, name, ms) {
const { promise, resolve, reject } = Promise.withResolvers();
const timer = setTimeout(() => {
target.removeEventListener(name, onEvent);
reject(new Error(`timed out waiting for "${name}"`));
}, ms);
function onEvent(event) {
clearTimeout(timer);
resolve(event);
}
target.addEventListener(name, onEvent, { once: true });
return promise;
}
try {
await waitForEventWithTimeout(new EventTarget(), "never", 20);
} catch (error) {
console.log(error.message);
}timed out waiting for "never"Both paths clean up: the event handler clears the timer, and the timer removes the handler. For simple cases, AbortSignal.timeout(ms) can supply the deadline, as shown in waiting for multiple events.
A reusable deferred value
A deferred is also a handy way to represent a value that is not ready yet, such as the result of an initialization that several parts of the code wait for. Create it once at module level and resolve it when the setup completes.
const config = Promise.withResolvers();
export const configReady = config.promise;
export function setConfig(value) {
config.resolve(value);
}
// elsewhere, long before or after setConfig is called:
setTimeout(() => setConfig({ region: "eu" }), 10);
console.log(await configReady);
console.log(await configReady);{ region: 'eu' }
{ region: 'eu' }Any number of callers can await configReady, before or after it settles, and all receive the same value. Calling resolve a second time has no effect, so a double initialization does not change the result, which is usually the behavior you want but can hide a bug if you expected an error.
A fallback for older runtimes
If you must run on a runtime without Promise.withResolvers, a three-line helper gives the same shape, and you can install it only when the method is missing.
Promise.withResolvers ??= function withResolvers() {
let resolve, reject;
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
};
const { promise, resolve } = Promise.withResolvers();
resolve(1);
console.log(await promise);1Libraries should not patch globals, so in shared code export the helper as a function instead and import it where needed. In an application, a polyfill at startup is fine. Check the MDN compatibility table for the browsers you support.
When to prefer the executor
The executor form is still better when the promise's whole life fits inside the callback, such as wrapping a single callback API. It also has one safety property the deferred lacks: if the executor throws, the promise rejects automatically. With a deferred, code that runs outside the executor and throws does not touch the promise, so it would never settle. Wrap risky setup in a try and call reject yourself.
Using it to hand work between functions
A deferred is most useful when the code that waits and the code that settles are different functions that cannot share a closure. A request tracker is a good example. A function sends a message over a socket and needs the matching reply, which arrives later in a general message handler. The sender creates a deferred, stores its resolve and reject in a map keyed by the request id and returns the promise. The message handler looks up the id and settles the right promise. Neither function needs to know about the other beyond the map.
That pattern replaces a tangle of callbacks with an ordinary await at the call site, and it also gives you one place to add a timeout and to reject every pending request when the socket closes. If you skip that last step, callers waiting on a dead socket wait forever, which is the most common bug in hand-written request trackers. Keep the map small and delete each entry as soon as its promise settles, so the map does not grow for the lifetime of the connection.
Pitfalls to watch for
Forgetting to settle. A deferred that nobody resolves or rejects is a promise that never settles, and the code awaiting it hangs silently. Every path that creates a deferred should have a matching path that settles it, including error paths and shutdown.
Settling twice by mistake. Because extra calls are ignored, two code paths that both think they own the outcome can race, and the loser's value is dropped without a warning. When that matters, track a settled flag and log when a second settlement is attempted.
Unhandled rejections. If you reject a deferred before anyone awaits it, Node.js can report an unhandled rejection. Attach a handler or an await before the rejection can happen, or create the promise lazily when the first consumer asks for it.
Leaking listeners. A listener that is never removed keeps the target alive and keeps calling a function whose promise has already settled. Remove every listener you add, using { once: true } or an explicit cleanup, as in the image example.
Testing code that uses a deferred
Deferred promises make tests easier as well as code. A test can create its own deferred, pass the promise to the code under test in place of a real network call, and decide exactly when to resolve it. That makes it possible to assert on the intermediate state, such as a loading flag that must be true while the request is pending and false afterward, with no timers and no flakiness. The same technique reproduces race conditions on demand: resolve the second request before the first and check which result the code keeps.


