FrontendPro

39Implement Promise.any() with AggregateError

mediumAbout 35 minutesCodingpromisesasyncerrors

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"), with errors in input order, not timing order.
  • An empty input rejects right away with an AggregateError and an empty errors array.
  • 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.

solution.jsJavaScript

Press Run or ⌘ Enter to execute your code.

Video walkthrough

Stuck? Watch someone solve it, then try again on your own.

25 Polyfill for promise methods all, allSettled, any & race | Javascript interview question in HindiCODERS NEVER QUIT on YouTubeOpen on YouTube

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.

All 150 answersOne payment, yours forever