HomePremium · ₹1199
← All questions

Implement Promise.all

Medium
Asked at:AmazonMicrosoft
Was this asked in an interview?

Build a Promise.all polyfill that resolves to an ordered array and rejects fast on the first failure.

Problem

Implement promiseAll(promises) — your own version of Promise.all.

You are aggregating several independent async calls (e.g. fetching a user, their orders, and their cart in parallel) and need all of them before rendering. promiseAll takes an array of values (promises or plain values) and returns a single promise that:

  • Resolves to an array of results in the same order as the input — regardless of which promise settles first.
  • Rejects immediately with the reason of the first promise that rejects (fail-fast); it does not wait for the rest.
  • Treats non-promise values as already-resolved.
  • Resolves to [] for an empty input array.

Input

const delay = (v, ms) => new Promise((r) => setTimeout(() => r(v), ms));

promiseAll([delay(1, 30), delay(2, 5), delay(3, 15)]).then(console.log);
promiseAll([Promise.resolve(1), Promise.reject("boom")]).catch(console.log);

Expected output

  • First call resolves to [1, 2, 3] (input order preserved even though 2 settles first).
  • Second call rejects with "boom".

Implement from scratch:

function promiseAll(promises) {
  // Your code here
}
Implement Promise.all — JavaScript Interview Question | Mentoxis