JavaScript Promise.withResolvers()
Description
Promise.withResolvers()
is a static method that simplifies the creation and management of Promises.
Promise.withResolvers() provides a more convenient way to access
the resolve and reject functions associated with a Promise outside of its executor function.
Example
const { promise, resolve, reject } = Promise.withResolvers();
// You can now use 'resolve' and 'reject' anywhere in your code
// to control the state of 'promise'.
// Simulate async work
setTimeout(() => {
const success = Math.random() > 0.5;
if (success) {
resolve("Operation successful!");
} else {
reject("Operation failed!");
}
}, 1000);
promise
.then((message) => text = message))
.catch((error) => text = error);
Instead of the traditional new Promise((resolve, reject) => { ... }) constructor pattern, Promise.withResolvers() returns an object containing:
- promise: The newly created Promise instance
- resolve: A function to fulfill the promise with a value
- reject: A function to reject the promise with a reason (error)
Syntax
Promise.withResolvers()
Parameters
| NONE |
Return Value
| Type | Description |
| Object |
An Object containing 3 properties: 1. A Promise Object. 2. A function that resolves the promise. 3. A function that rejects the promise. |
Promise Methods
Static Methods
Promise.all()
Promise.allSettled()
Promise.any()
Promise.race()
Promise.reject()
Promise.resolve()
Promise.try()
Promise.withResolvers()
See Also:
Browser Support
Promise.withResolvers() is a JavaScrip 2024 feature.
ES 2024 is supported in all modern browsers since March 2024:
| Chrome 117 |
Edge 117 |
Firefox 119 |
Safari 17.4 |
Opera 103 |
| Sep 2023 | Sep 2023 | Oct 2023 | Okt 2024 | May 2023 |