JavaScriptFundamental (ES6), part 2
Process promises as they complete in JavaScript
50 Results as they complete, not in order
hardWrite asCompleted(tasks), an async generator that yields each result the moment it settles, tagged with its index. Drive three tasks of different lengths from an injected clock and show the fastest arriving first, while Promise.all over the same promises still reports input order.
Stuck? Three hints, smallest first
- 1. Keep a
Mapfrom index to a promise that resolves to{ index, value }or{ index, reason }— never rejects. - 2.
Promise.raceover the remaining entries gives you the next one to settle; delete it and race again. - 3. Wrapping each task so it cannot reject is what stops one failure from ending the stream.
function manualClock() {
let now = 0;
const timers = [];
return {
get time() { return now; },
get pending() { return timers.length; },
wait(ms) { return new Promise((resolve) => timers.push({ at: now + ms, resolve })); },
async advance(ms) {
now += ms;
for (const timer of timers.filter((t) => t.at <= now)) {
timers.splice(timers.indexOf(timer), 1);
timer.resolve();
}
for (let i = 0; i < 20; i++) await Promise.resolve(); // let the waiters run
},
};
}
async function* asCompleted(tasks) {
const pending = new Map(
tasks.map((task, index) => [
index,
Promise.resolve(task).then(
(value) => ({ index, value }),
(reason) => ({ index, reason }) // a failure is a result, not an exit
),
])
);
while (pending.size) {
const settled = await Promise.race(pending.values());
pending.delete(settled.index);
yield settled;
}
}
const clock = manualClock();
const after = (ms, name) => clock.wait(ms).then(() => name);
const tasks = [after(300, 'ikeja'), after(100, 'yaba'), after(200, 'lekki')];
const arrivals = [];
const draining = (async () => {
for await (const settled of asCompleted(tasks)) arrivals.push([settled.index, settled.value]);
})();
await clock.advance(100);
const firstOut = arrivals.slice();
await clock.advance(100);
await clock.advance(100);
await draining;
const inInputOrder = await Promise.all(tasks);
const second = manualClock();
const later = (ms, name) => second.wait(ms).then(() => name);
const breaks = (ms, message) => second.wait(ms).then(() => { throw new Error(message); });
const mixed = [];
const withFailure = (async () => {
for await (const settled of asCompleted([later(300, 'ikeja'), breaks(100, 'yaba offline'), later(200, 'lekki')])) {
mixed.push(settled.reason ? 'ERR ' + settled.reason.message : settled.value);
}
})();
await second.advance(100);
await second.advance(100);
await second.advance(100);
await withFailure;
const nothing = [];
for await (const settled of asCompleted([])) nothing.push(settled);
console.log('first out :', firstOut);
console.log('all arrivals :', arrivals);
console.log('Promise.all :', inInputOrder);
console.log('with a failure:', mixed);
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('the first result out is the fastest, not the first in the list', firstOut, [[1, 'yaba']]);
test('everything arrives, in the order it finished', arrivals.map((a) => a[1]), ['yaba', 'lekki', 'ikeja']);
test('each result knows which input it came from', arrivals.map((a) => a[0]), [1, 2, 0]);
test('while Promise.all over the very same promises reports input order', inInputOrder, ['ikeja', 'yaba', 'lekki']);
test('a rejection is yielded as data and the stream carries on', mixed, ['ERR yaba offline', 'lekki', 'ikeja']);
test('so every input is accounted for, failures included', mixed.length, 3);
test('an empty list ends the loop immediately', nothing, []);
test('and no timer is left behind on either clock', [clock.pending, second.pending], [0, 0]);
Promise.all makes you wait for the slowest before you can use the fastest. That is right when the results are one thing — a page that needs all three lookups — and wrong when they are independent: three thumbnails, three receipts, three rows to stream into a table. This generator gives you each one at the moment it is ready, and the second assertion is the difference in one line: yaba at 100ms rather than everything at 300ms.
The design decision is the wrapping. Each task is turned into a promise that cannot reject, carrying either a value or a reason, which is what lets one failure be yielded and stepped over instead of ending the loop the way a rejection inside for await does in exercise 16. The index travels with it because completion order destroys the correlation you get free from an array — without it, you know a result arrived but not what it was for.
Two details in the loop. Promise.race is called afresh each round over only the remaining entries, so a settled promise is never raced again — leave it in the map and the race returns the same result for ever. And the Map is keyed by index rather than by promise, so delete is exact even if two tasks are the same promise object.
The clock is stepped 100ms at a time on purpose. Advancing 300ms in one jump resolves all three timers in the same instant, and the completion order would then be the order they were created — which would make the test pass for the wrong reason.