MENU
Promise.withResolvers()
Promise.withResolvers(), added in ECMAScript 2024, is a static convenience method that returns a plain object {promise, resolve, reject}: a new Promise together with its resolve and reject functions extracted right alongside it, instead of the executor-callback dance required by 'new Promise((resolve,reject)=>{...})' (5.1).
This is handy whenever the code that resolves/rejects a promise lives outside the scope where the promise itself is created, eg. storing pending requests in a Map keyed by request id.
const pending = new Map();
function request(id) {
const {promise, resolve, reject} = Promise.withResolvers();
pending.set(id, {resolve, reject});
return promise;
}
function onServerMessage(id, err, data) { // called later, from a totally different scope
const {resolve, reject} = pending.get(id);
pending.delete(id);
err ? reject(err) : resolve(data);
}
request(1).then(data => console.log('got:', data));
onServerMessage(1, null, 'hello');got: hello
Before this method existed, the same {promise, resolve, reject} shape had to be built manually:
let resolve, reject;
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});