FrontendDeveloper.in

ECMAScript question detail

Promise withResolvers

When you are creating a new Promise object, usually you pass resolve and reject functions to the executor of promise constructor as shown below:

const promise = new Promise((resolve, reject) =>{
setTimeout(() =>  { Math.random() > 0.5 ? resolve("Success") : reject("Error")}, 1000);
});
promise.then(result => console.log(result)).catch(error => console.error(error));

In this constructor pattern, it is possible call the resolve and reject functions inside the promise constructor only. But if you want these functions outside of the promise constructor, you often have to write the following boilerplate code.

let resolve, reject;
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});

setTimeout(() =>  { Math.random() > 0.5 ? resolve("Success") : reject("Error")}, 1000);
promise.then(result => console.log(result)).catch(error => console.error(error));

The above code is simplified with Promise.withResolvers() in ES2024, it's a static method factory that returns an object containing a new Promise along with two functions one for resolve and other one for reject. These two functions corresponding to the two parameters passed to the executor of the Promise() constructor shown in the initial code snippets.

The concise version of earlier code snippet looks like below,

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

setTimeout(() =>  { Math.random() > 0.5 ? resolve("Success") : reject("Error")},1000);
promise.then(result => console.log(result)).catch(error => console.error(error));

ES2025 or ES16

ES2025 is planned to be released in June 2025 with several new features and enhancements for JavaScript developers. These features aim to improve developer productivity and code readability.

Back to all ECMAScript questions
Get LinkedIn Premium at Rs 399