coding round · ~20 min
JavaScriptadvanced

Implement Promise.all

Write promiseAll(iterable) that behaves like Promise.all, without calling it. It returns a promise that:

  • resolves with an array of results in the same order as the input, no matter which item settles first
  • treats non-promise values (and thenables) as already-resolved values
  • resolves with [] for an empty input
  • rejects as soon as any item rejects (fail fast), with that same reason

It should accept any iterable, such as an array, a Set or a generator.

  • promiseAll([1, Promise.resolve(2), 3]) → resolves to [1, 2, 3]
  • promiseAll([slow, fast]) → resolves to [slowResult, fastResult], even though fast settles first
  • promiseAll([]) → resolves to []
  • promiseAll([neverSettles, Promise.reject(err)]) → rejects with err right away

Define promiseAll in the editor. 8 tests will call it.

read the related note →

solution.js
function promiseAll(iterable) {
  // Return a promise that resolves with every result, in input order,
  // or rejects as soon as one of the inputs rejects.
}

Tests⌘/Ctrl + Enter to run

returns a promise
resolves values in input order, not completion order
passes through plain values and thenables
resolves an empty input with []
rejects as soon as one input rejects
rejects with the first rejection reason
accepts any iterable
works without calling Promise.all
esc