AniUI Academy

Re-implement Promise.all from Scratch

hardAsync & PromisesHigh freq+300 XPFrontend AlgoArena

Promise.all is the primitive you reach for when a page needs to wait on several independent requests before it can render. Reimplementing it from scratch is a common interview question because it forces you to reason about async composition without a library doing the hard part.

Implement promiseAll(promises) that resolves with an array of each promise's resolved value — in the original input order — once every input has settled. If any input rejects, promiseAll must reject immediately with that error.

Arguments

promisesArray<Promise | any>
An array of promises or plain values.

Returns

Promise<Array> — A promise that resolves with an array of settled values, in input order. Rejects with the first error encountered.

Examples

const result = await promiseAll([
  Promise.resolve(10),
  new Promise((r) => setTimeout(() => r(20), 10)),
  30, // plain value
]);
// result === [10, 20, 30]

Plain values pass through as if wrapped in Promise.resolve.

try {
  await promiseAll([
    Promise.resolve(1),
    Promise.reject("boom"),
    Promise.resolve(3),
  ]);
} catch (err) {
  // err === "boom" — the first rejection wins
}

What it has to do

  • Resolve with an array of values in original input order.
  • Reject immediately if any input promise rejects.
  • Handle non-promise values seamlessly.

Notes

  • An empty input must resolve immediately with an empty array — a common off-by-one bug.
  • Promises resolve asynchronously, so track completion with a counter rather than checking the output array for undefined holes.
Asked atMetaGoogleAmazonMicrosoftUber
Try it yourself
Loading playground...
2 tests · +300 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.