Implement Promise.all
This question tests whether you understand Promise mechanics beyond just .then() and async/await.
Implementation
function promiseAll(promises) {
return new Promise((resolve, reject) => {
const results = [];
let settled = 0;
const items = Array.from(promises);
if (items.length === 0) {
resolve([]);
return;
}
items.forEach((promise, index) => {
Promise.resolve(promise).then(
(value) => {
results[index] = value;
settled++;
if (settled === items.length) resolve(results);
},
(reason) => {
reject(reason);
}
);
});
});
}Key Details to Discuss
- Order preservation â results must match input order, not resolution order
- Non-promise values â
Promise.resolve()wraps them correctly - Empty array â should resolve immediately with
[] - First rejection wins â any rejection short-circuits the entire promise
- Iterable input â
Array.from()handles any iterable
Follow-Up: Promise.allSettled
function promiseAllSettled(promises) {
return new Promise((resolve) => {
const results = [];
let settled = 0;
const items = Array.from(promises);
if (items.length === 0) {
resolve([]);
return;
}
items.forEach((promise, index) => {
Promise.resolve(promise).then(
(value) => {
results[index] = { status: 'fulfilled', value };
settled++;
if (settled === items.length) resolve(results);
},
(reason) => {
results[index] = { status: 'rejected', reason };
settled++;
if (settled === items.length) resolve(results);
}
);
});
});
}When to Use Which
| Method | Behavior | Use Case |
|---|---|---|
Promise.all | Fail fast on first rejection | All-or-nothing operations |
Promise.allSettled | Wait for all, never rejects | Independent operations with graceful degradation |
Promise.race | First to settle wins | Timeouts, fastest source |
Promise.any | First fulfillment wins | Fallback data sources |
The senior signal: knowing which Promise combinator to use for a given problem is more valuable than implementing them.