JavaScriptFundamental (ES6), part 2
Create a deferred promise in JavaScript
44 A deferred, and a promise for the next event
fairBuild a deferred() whose resolve and reject can be called from outside, then use it to write once(source): the next event from a small emitter, as a promise, with the listener removed again. Find the two ways a deferred goes wrong.
Stuck? Three hints, smallest first
- 1. The
Promiseexecutor runs synchronously, so assigningresolveout of it is safe to use immediately after. - 2.
oncemust unsubscribe inside its own handler, or every waiter leaves a listener behind. - 3. A settled promise is final, and a promise nobody settles produces no error at all.
function deferred() {
let resolve;
let reject;
const promise = new Promise((res, rej) => { resolve = res; reject = rej; });
return { promise, resolve, reject };
}
function emitter() {
const handlers = [];
return {
on(fn) { handlers.push(fn); },
off(fn) { const at = handlers.indexOf(fn); if (at !== -1) handlers.splice(at, 1); },
emit(value) { for (const fn of handlers.slice()) fn(value); },
get listeners() { return handlers.length; },
};
}
// The next event, as a promise, cleaning up after itself.
function once(source) {
const { promise, resolve } = deferred();
const handler = (value) => { source.off(handler); resolve(value); };
source.on(handler);
return promise;
}
const gate = deferred();
let arrived = 'nothing yet';
gate.promise.then((value) => { arrived = value; });
for (let i = 0; i < 3; i++) await Promise.resolve();
const beforeResolve = arrived;
gate.resolve('opened');
const firstValue = await gate.promise;
gate.resolve('opened again');
const afterSecondResolve = await gate.promise;
const tills = emitter();
const next = once(tills);
const listenersWhileWaiting = tills.listeners;
tills.emit('till 3 opened');
const first = await next;
const listenersAfter = tills.listeners;
const failing = deferred();
failing.reject(new Error('till 4 never opened'));
const rejected = await failing.promise.catch((err) => err.message);
const forgotten = deferred();
let everSettled = false;
forgotten.promise.then(() => { everSettled = true; }, () => { everSettled = true; });
for (let i = 0; i < 8; i++) await Promise.resolve();
const late = emitter();
late.emit('fired before anyone subscribed');
const missed = await Promise.race([once(late), Promise.resolve('nothing arrived')]);
console.log('before resolve :', beforeResolve, '-> after:', firstValue);
console.log('listeners :', listenersWhileWaiting, 'while waiting,', listenersAfter, 'after');
console.log('rejected :', rejected);
console.log('never settled :', everSettled, '- missed event:', missed);
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a deferred stays pending until someone outside settles it', beforeResolve, 'nothing yet');
test('and then carries the value they passed', firstValue, 'opened');
test('a second resolve changes nothing: settled is final', afterSecondResolve, 'opened');
test('once() hands you the next event as a promise', first, 'till 3 opened');
test('and unsubscribes itself, so waiting does not leak a listener', [listenersWhileWaiting, listenersAfter], [1, 0]);
test('reject works from outside in exactly the same way', rejected, 'till 4 never opened');
test('a deferred nobody settles stays pending for ever, with no warning', everSettled, false);
test('and an event fired before you subscribed is simply gone', missed, 'nothing arrived');
A deferred inverts the Promise constructor: instead of the work living inside the executor, the settling functions escape it and someone else decides. That is exactly what you need at the boundary between a callback API and a promise one — once is eleven lines and turns any emitter into something you can await. The platform now ships this as Promise.withResolvers(), which returns the same three fields; the hand-rolled version is worth writing once so the built-in holds no mystery.
The listener assertion is the part that separates a working once from a leaking one. Without source.off(handler), every caller who awaits an event leaves a closure attached to the emitter for the lifetime of the page — the classic slow leak in a component that subscribes on every render. Note also that emit iterates a copy of the handler list, because a handler that removes itself would otherwise shift the array mid-loop and skip the next one.
The last two assertions are the two failure modes, and neither one reports itself. A deferred nobody settles is not an error: it is a promise that stays pending, an await that never returns, and no warning anywhere. And an event that fires before you subscribe is missed entirely, which is why once must be called before whatever triggers the event, not after. Where you cannot guarantee that ordering, you want the buffered bridge from exercise 17 instead.