Implement Promise.all
You fire off three requests and need all three answers before you can render the page. You also need them in the order you asked, even though the network will finish them in whatever order it likes.
Promise.all takes an array of promises and returns a single promise. It
fulfils once every input promise has fulfilled, with an array of their
results in input order — regardless of which settles first. If any input
rejects, the whole thing rejects with that reason.
Building it by hand shows the two ideas underneath. First, kick off every promise immediately — do not await them one at a time. Second, count the settlements and only resolve once the count reaches the total:
function promiseAll(promises) {
return new Promise((resolve, reject) => {
const results = [];
let remaining = promises.length;
if (remaining === 0) return resolve(results);
promises.forEach((promise, index) => {
promise.then((value) => {
results[index] = value; // keep input order
remaining -= 1;
if (remaining === 0) resolve(results);
}, reject); // the first rejection wins
});
});
}
Writing each result into results[index] keeps the output aligned with the
input even when a later promise settles first. Handing reject straight to
.then means the first failure rejects the outer promise, and the rest are
ignored.
Export promiseAll from index.js. Your job is to resolve with every result
in order and reject on the first failure.
Challenge
Several promises are in flight and you need every result before you can move on — collected in the order you passed them, not the order they happen to finish.
Export a promiseAll function from index.js. It takes an array of promises
and returns a single promise that fulfils with an array of every result in
input order, once all the inputs have fulfilled. If any input rejects, the
returned promise must reject with that same reason. Do not use the built-in
Promise.all.