Promise.withResolvers
Creates a promise and hands out its resolve and reject functions.
Available since: ES2024
Syntax
Promise.withResolvers()Return value
objectAn object with promise, resolve and reject fields.
Examples
Resolving a promise from elsewhere in the code:
const { promise, resolve } = Promise.withResolvers();
setTimeout(() => resolve('done'), 50);
console.log(await promise);Output:
doneNotes
It is a shorthand for the old trick of saving resolve into a variable inside new Promise(...). Handy when a promise is resolved by an event.
See also
- Promise — A promise of a result that will be ready later: success or failure.
- Promise.resolve — Creates a promise that is already fulfilled with a value.
In the tutorial
- Promises — Promises in JavaScript: promise states, then, catch, finally, creating a promise with new Promise, and chains.