Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Promises and Async

Promise.withResolvers()

Reference for Promise.withResolvers(): create a promise together with its resolve and reject functions, ideal for events, queues and deferred results.

Promise.withResolvers() returns an object with three properties: a new pending promise, and the resolve and reject functions that settle it. You no longer need the old trick of declaring variables outside and assigning them from inside the executor.

This is useful when the code that settles a promise lives somewhere else than the code that creates it, for example in an event handler, a queue or a message listener.

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

Try it

JS Settling from outside

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

No output.

JS A tiny async queue

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

No output.

Syntax

JavaScript
Promise.withResolvers()

This method takes no arguments.

Return value: a plain object with these properties:

Property Description
promise A new pending Promise.
resolve A function that resolves promise with a value.
reject A function that rejects promise with a reason.

Exceptions: none for the standard use. When called on a subclass or another constructor via call(), that constructor must behave like a promise constructor, or a TypeError is thrown.

Usage notes

  • Equivalent to creating new Promise((res, rej) => { resolve = res; reject = rej; }) with outer variables, but shorter and without the temporary lets.
  • Settle once. As with any promise, only the first call to resolve() or reject() has an effect.
  • No executor safety net. Errors thrown in your surrounding code do not reject the promise automatically, so catch them and call reject() yourself.
  • Destructure at the call site. Keep the three parts together in an object if you pass them around, so that the pairing stays clear.
  • Use sparingly. If the work can be written inside a new Promise() executor or an async function, that is simpler and safer.
  • Leaks. A promise whose resolver is never called stays pending forever, and so do any handlers waiting on it.

Browser support

This is a recent addition. It is supported in current browsers and Node.js, but not in older ones, so check a compatibility table, and use the manual pattern as a fallback.