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 likePromise.all.myAllSettled(promises)behaves likePromise.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.allorPromise.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.raceandPromise.any? - How would you accept any iterable instead of only arrays?