Implement Promise.all
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Implement promiseAll(iterable), your own version of Promise.all. It takes an array of promises (or plain values) and returns a promise that:
- resolves with an array of all the results, in the same order as the input, once every promise has resolved;
- rejects with the reason of the first promise that rejects, as soon as it does.
const slow = new Promise((resolve) => setTimeout(() => resolve('slow'), 200))
const fast = new Promise((resolve) => setTimeout(() => resolve('fast'), 50))
await promiseAll([slow, fast, 42])
// ['slow', 'fast', 42]: input order, not finish order
await promiseAll([fast, Promise.reject(new Error('Oops'))])
// rejects with Error: OopsRequirements
- Always return a promise.
- Results keep the order of the input, no matter which promise finishes first.
- Plain values (not promises) count as already resolved.
- Reject with the first rejection reason. Later rejections are ignored.
- An empty array resolves with
[].
Note
Don't use Promise.all, Promise.allSettled or Promise.any: implementing that logic is the exercise. new Promise and Promise.resolve are fine.
Approach
Return a new Promise and keep two pieces of state in its executor:
results: an array the size of the input, filled by index.remaining: how many items have not resolved yet.
Then subscribe to every item:
- Wrap it in
Promise.resolve(item), so plain values and promises are handled the same way. - When it resolves, store the value at its own index (not with
push, which would record finish order), and decrementremaining. When it reaches0, resolve withresults. - When it rejects, call
rejectwith the reason.
Why rejecting "only once" is free
A promise settles once. After the first reject (or resolve), further calls to either one do nothing, so the later rejections need no extra bookkeeping.
Edge cases
- Empty input: no item ever resolves, so
remainingwould never reach0from a callback. Resolve with[]right away. asyncfunctions: writing the outer function asasyncandawaiting each item in a loop gets the order right but runs them in sequence and reports a rejection late. Subscribe to all of them first.
Complexity
O(n) time and space for n items, on top of the work the promises do. The total wait is as long as the slowest promise, because they all run at the same time.
Follow-ups interviewers ask
Promise.allSettled: never reject; collect{ status, value }or{ status, reason }for every item.Promise.raceandPromise.any: settle with the first result, or the first success.- Concurrency limit: run a list of async tasks with at most
kin flight at once, which is a common next question.
Reference solution
/**
* @param {Array<*>} iterable
* @returns {Promise<Array<*>>}
*/
export default function promiseAll(iterable) {
return new Promise((resolve, reject) => {
const items = Array.from(iterable)
const results = new Array(items.length)
let remaining = items.length
if (remaining === 0) {
resolve(results)
return
}
items.forEach((item, index) => {
Promise.resolve(item).then((value) => {
results[index] = value
remaining -= 1
if (remaining === 0) resolve(results)
}, reject)
})
})
}export default function promiseAll<T>(iterable: Array<T | PromiseLike<T>>): Promise<T[]> {
return new Promise((resolve, reject) => {
const items = Array.from(iterable)
const results = new Array<T>(items.length)
let remaining = items.length
if (remaining === 0) {
resolve(results)
return
}
items.forEach((item, index) => {
Promise.resolve(item).then((value) => {
results[index] = value
remaining -= 1
if (remaining === 0) resolve(results)
}, reject)
})
})
}