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
Promise.withResolvers.resolve/reject.resolve and reject behave exactly like the ones passed to a Promise executor: only the first call has any effect, and resolve adopts promises and thenables.promise, resolve and reject.new Promise(executor)? Name two real use cases.resolve/reject around freely?Spotted a mistake or a rights concern? Report an issue