Implement Promise.any from scratch
Three CDNs host the same asset. You want whichever answers successfully first, and you only want to show an error if all three are down. Promise.race cannot do this: it settles on the first rejection.
Implement any(promises) without using Promise.any. It resolves with the value of the first input to fulfil, ignoring any rejections before that. If every input rejects, reject with an Error whose message is exactly "All promises were rejected" and whose errors property is an array of the rejection reasons in input order. An empty array rejects the same way, with errors set to an empty array. Non-promise entries count as already fulfilled.
Arguments
promisesArray<Promise | any>- An array of promises or plain values.
Returns
Promise<any> — A promise that resolves with the first fulfilment. Rejects with an Error carrying an errors array only when every input rejects.
Examples
const failing = Promise.reject("cdn-a down");
failing.catch(() => {});
const value = await any([
failing,
new Promise((resolve) => setTimeout(() => resolve("ok"), 20)),
]);
// value === "ok" — the earlier rejection is ignoredFalls through rejections to find the first success.
try {
const a = Promise.reject("a");
const b = Promise.reject("b");
a.catch(() => {}); b.catch(() => {});
await any([a, b]);
} catch (error) {
// error.message === "All promises were rejected"
// error.errors === ["a", "b"]
}Collected reasons sit on the thrown error's errors property.
What it has to do
- Resolve with the first fulfilled value, whatever order the inputs settle in.
- Ignore rejections while any input can still fulfil.
- Reject with an
Errorwhose message isAll promises were rejectedwhen all inputs reject. - Put the rejection reasons on the error's
errorsproperty, in input order. - Reject with an empty
errorsarray for an empty input array.
Notes
- Count the rejections rather than the fulfilments — store each reason at its index and only reject once the counter reaches the input length.
- An empty input rejects immediately with an empty
errorsarray; forgetting that edge case is a common off-by-one bug.
Stuck? The javascript course covers everything this challenge needs.
- 1.resolves with the first fulfilment even after a rejection
- 2.rejects with the collected errors when all fail
- 3.rejects with an empty errors array for empty input
- 4.treats a plain value as an immediate success
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.