Home
← All questions

Promise.all and Promise.allSettled implementation in JavaScript

MediumPremiumJavaScript

JavaScript interview practice: Implement polyfills for Promise.all and Promise.allSettled.

Problem

Dashboards that load several APIs in parallel depend on these combinators, and a Promise.all and Promise.allSettled implementation in JavaScript is a frequent frontend interview question.

Write two functions that take an array of promises (or plain values) and return a promise:

  • myAll(promises) behaves like Promise.all.
  • myAllSettled(promises) behaves like Promise.allSettled.

Requirements

myAll

  • Resolves with an array of all fulfilled values once every input has fulfilled.
  • Results are in input order, not in the order the promises settle.
  • Rejects as soon as any input rejects, with that input's rejection reason.

myAllSettled

  • Never rejects; resolves once every input has settled.
  • Each result is { status: "fulfilled", value } or { status: "rejected", reason }, in input order.

Both

  • Non-promise values in the array are treated as already fulfilled.
  • An empty array resolves immediately with [].
  • Do not use the built-in Promise.all or Promise.allSettled.

Example

const slow = new Promise((r) => setTimeout(() => r("slow"), 50));
const fast = Promise.resolve("fast");

myAll([slow, fast, 3]).then(console.log);
// ["slow", "fast", 3]

myAll([fast, Promise.reject(new Error("boom"))]).catch((e) => console.log(e.message));
// "boom"

myAllSettled([slow, Promise.reject("nope")]).then(console.log);
// [
//   { status: "fulfilled", value: "slow" },
//   { status: "rejected", reason: "nope" }
// ]

myAll([]).then(console.log); // []

Follow-ups

  • How would you implement Promise.race and Promise.any?
  • How would you accept any iterable instead of only arrays?
Premium question

Unlock the in-browser editor, test cases, and model solution with Mentoxis Premium.

Unlock with Premium