Promise.withResolvers
JS Functions
Easy
10 min
promises
async
polyfills
closures
Implement promiseWithResolvers(), which behaves like Promise.withResolvers (ES2024). It returns an object { promise, resolve, reject }: a new pending promise plus the two functions that settle it, so code outside the executor can settle it later.
const { promise, resolve, reject } = promiseWithResolvers();
button.addEventListener('click', () => resolve('clicked'), { once: true });
setTimeout(() => reject(new Error('Too slow')), 5000);
await promise; // 'clicked' if the user clicked within 5 seconds
Requirements
- Do not use the native
Promise.withResolvers. - Every call returns a new promise with its own
resolve/reject. resolveandrejectbehave exactly like the ones passed to aPromiseexecutor: only the first call has any effect, andresolveadopts promises and thenables.- The returned object is a plain object with exactly the keys
promise,resolveandreject.
Follow-up
- What problem does this solve compared to
new Promise(executor)? Name two real use cases. - What are the risks of passing
resolve/rejectaround freely?
Spotted a mistake or a rights concern? Report an issue