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.
const { promise, resolve, reject } = Promise.withResolvers();
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
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 temporarylets. - Settle once. As with any promise, only the first call to
resolve()orreject()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 anasyncfunction, 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.