Skip to main content
07

Implement Promise.all

Mediumpromisesasync

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

Implement promiseAll(iterable), your own version of Promise.all. It takes an array of promises (or plain values) and returns a promise that:

  • resolves with an array of all the results, in the same order as the input, once every promise has resolved;
  • rejects with the reason of the first promise that rejects, as soon as it does.
js
const slow = new Promise((resolve) => setTimeout(() => resolve('slow'), 200))
const fast = new Promise((resolve) => setTimeout(() => resolve('fast'), 50))

await promiseAll([slow, fast, 42])
// ['slow', 'fast', 42]: input order, not finish order

await promiseAll([fast, Promise.reject(new Error('Oops'))])
// rejects with Error: Oops

Requirements

  • Always return a promise.
  • Results keep the order of the input, no matter which promise finishes first.
  • Plain values (not promises) count as already resolved.
  • Reject with the first rejection reason. Later rejections are ignored.
  • An empty array resolves with [].

Note

Don't use Promise.all, Promise.allSettled or Promise.any: implementing that logic is the exercise. new Promise and Promise.resolve are fine.

Approach

Return a new Promise and keep two pieces of state in its executor:

  • results: an array the size of the input, filled by index.
  • remaining: how many items have not resolved yet.

Then subscribe to every item:

  1. Wrap it in Promise.resolve(item), so plain values and promises are handled the same way.
  2. When it resolves, store the value at its own index (not with push, which would record finish order), and decrement remaining. When it reaches 0, resolve with results.
  3. When it rejects, call reject with the reason.
Loading diagram...

Why rejecting "only once" is free

A promise settles once. After the first reject (or resolve), further calls to either one do nothing, so the later rejections need no extra bookkeeping.

Edge cases

  • Empty input: no item ever resolves, so remaining would never reach 0 from a callback. Resolve with [] right away.
  • async functions: writing the outer function as async and awaiting each item in a loop gets the order right but runs them in sequence and reports a rejection late. Subscribe to all of them first.

Complexity

O(n) time and space for n items, on top of the work the promises do. The total wait is as long as the slowest promise, because they all run at the same time.

Follow-ups interviewers ask

  • Promise.allSettled: never reject; collect { status, value } or { status, reason } for every item.
  • Promise.race and Promise.any: settle with the first result, or the first success.
  • Concurrency limit: run a list of async tasks with at most k in flight at once, which is a common next question.

Reference solution

js
/**
 * @param {Array<*>} iterable
 * @returns {Promise<Array<*>>}
 */
export default function promiseAll(iterable) {
  return new Promise((resolve, reject) => {
    const items = Array.from(iterable)
    const results = new Array(items.length)
    let remaining = items.length

    if (remaining === 0) {
      resolve(results)
      return
    }

    items.forEach((item, index) => {
      Promise.resolve(item).then((value) => {
        results[index] = value
        remaining -= 1
        if (remaining === 0) resolve(results)
      }, reject)
    })
  })
}
ts
export default function promiseAll<T>(iterable: Array<T | PromiseLike<T>>): Promise<T[]> {
  return new Promise((resolve, reject) => {
    const items = Array.from(iterable)
    const results = new Array<T>(items.length)
    let remaining = items.length

    if (remaining === 0) {
      resolve(results)
      return
    }

    items.forEach((item, index) => {
      Promise.resolve(item).then((value) => {
        results[index] = value
        remaining -= 1
        if (remaining === 0) resolve(results)
      }, reject)
    })
  })
}