AniUI Academy

Implement Promise.any from scratch

mediumAsync & Promises+250 XPPractice

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 ignored

Falls 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 Error whose message is All promises were rejected when all inputs reject.
  • Put the rejection reasons on the error's errors property, in input order.
  • Reject with an empty errors array 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 errors array; forgetting that edge case is a common off-by-one bug.
Asked atGoogleMicrosoft

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
4 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.