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.
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.
Where it's been asked
- Microsoft
From public interview reports — a problem very like this one has shown up in a round at these companies. Not an exhaustive list.
Stuck? The javascript course covers everything this challenge needs.
Ready to check it?
4 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
Need a nudge?
Reveal a conceptual hint or the reference solution. Both were written and reviewed with the problem — no runtime magic.
Discussion
Sign in to postNo comments yet. Be the first to say something.