39Implement Promise.any() with AggregateError
Problem
Implement promiseAny(iterable) without using Promise.any. It fulfils with the value of the first item that fulfils. Rejections are ignored unless every item rejects; then it rejects with an AggregateError whose errors array holds every reason, in input order.
// Load an image from whichever CDN answers first.
const url = await promiseAny([probe(cdnA), probe(cdnB), probe(cdnC)]);Requirements
- Fulfil with the first fulfilment, even if other items rejected before it.
- If all items reject, reject with
new AggregateError(errors, "All promises were rejected"), witherrorsin input order, not timing order. - An empty input rejects right away with an
AggregateErrorand an emptyerrorsarray. - Items may be promises, thenables or plain values; accept any iterable.
Try it yourself
Write your solution, run it, then submit to check it against the tests.
Press Run or ⌘ Enter to execute your code.
Video walkthrough
Stuck? Watch someone solve it, then try again on your own.
Step-by-step
all collects fulfilments and fails on the first rejection. any collects rejections and succeeds on the first fulfilment. The structure of the code is the same with the roles swapped.
Unlock the full solution
What's inside
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Tests
Includes 2 code listings, 5 edge cases, 4 follow-up questions.
One-time payment by UPI, card or net banking. Launch price.