HomePremium · ₹1199
← All questions

Implement Promise.allSettled

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

Build a Promise.allSettled polyfill that never rejects and reports the status of every promise.

Problem

Implement promiseAllSettled(promises) — your own version of Promise.allSettled.

Unlike Promise.all, you often want to run several async operations and wait for all of them to finish, whether they succeed or fail — for example firing off analytics, a cache write, and an email, then reporting which ones worked. promiseAllSettled takes an array of values (promises or plain values) and returns a single promise that:

  • Never rejects — it always resolves.
  • Resolves to an array (in input order) of outcome objects:
    • { status: "fulfilled", value } for resolved promises / plain values, or
    • { status: "rejected", reason } for rejected ones.
  • Resolves to [] for an empty input array.

Input

promiseAllSettled([
  Promise.resolve(1),
  Promise.reject("x"),
  3,
]).then(console.log);

Expected output

[
  { status: "fulfilled", value: 1 },
  { status: "rejected", reason: "x" },
  { status: "fulfilled", value: 3 },
]

Implement from scratch:

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