CodePark/ problems / Promise.any
START PRACTICINGPRACTICE
Coding problem · JavaScript utilities › Promise combinators

Promise.any

hardabout 25 minutes in an interview

Implement promiseAny(items), your own version of Promise.any. Don't call Promise.any or the other built-in combinators: Promise.all, Promise.allSettled and Promise.race.

items is an array of promises and plain values. An item fulfils when it resolves with a value. Return a promise that follows these rules:

  • It resolves with the value of the first item to fulfil, and ignores any earlier rejections. A plain value counts as fulfilled.
  • If every item rejects, it rejects with an AggregateError or any other Error. The error's errors property holds all the reasons in input order, not in rejection order.
  • For an empty array, it rejects straight away with the same kind of error, and errors equals [].
Input: await promiseAny([Promise.reject('a'), wait(20, 'b'), wait(10, 'c')]) Output: 'c'
Input: await promiseAny([Promise.reject('x'), Promise.reject('y')]) Output: rejects with an error whose errors is ['x', 'y']