FrontendArk

Master Frontend Interviews

  • Practice
  • Playground
  • Resource
Medium

Promise.any

20mins

Implement a function promiseAny(promises) that behaves like Promise.any() but accepts an array instead of an iterable.

  • The function returns a Promise that resolves as soon as any input promise fulfills, with that fulfillment value.
  • If all input promises reject, the returned Promise rejects with an AggregateError-like object whose errors property is an array of rejection reasons (in the same order as the input array).
  • If the input array is empty, the returned Promise must be rejected immediately with an AggregateError-like object whose errors is an empty array.
  • Non-promises should be treated like Promise.resolve(value).

Examples

const p0 = Promise.resolve(42); const p1 = new Promise((resolve) => setTimeout(() => resolve(21), 100)); await promiseAny([p0, p1]); // 42 const p0 = new Promise((resolve) => setTimeout(() => resolve(42), 100)); const p1 = new Promise((_, reject) => setTimeout(() => reject('Err!'), 50)); await promiseAny([p0, p1]); // 42 // If all reject: const p0 = new Promise((_, reject) => setTimeout(() => reject(42), 50)); const p1 = new Promise((_, reject) => setTimeout(() => reject('Err!'), 10)); try { await promiseAny([p0, p1]); } catch (e) { // e.errors should be [42, 'Err!'] (errors in input order) }

Code Editor

JavaScript Function

00:00
Loading...

Test Cases

No test results yet

Click "Run" to execute tests