QuestionsJavaScript

Implement Promise.all

Implement from scratchHardJavaScript

Implement Promise.all(promises): resolve with an array of results in order, or reject on the first rejection.

What it tests

Async coordination, preserving order, the count-down-to-done pattern, and fail-fast semantics.

Approach & answer

Return a new Promise. Track a results array and a completed counter. For each input, resolve it (Promise.resolve wraps non-promises), write its result at its ORIGINAL index (not push — they finish out of order, order must be preserved), and when the counter hits the length, resolve. Any rejection rejects the outer promise immediately (fail-fast). Handle the empty-array case by resolving with []. Two correctness details interviewers look for: use a completed counter, NOT results.length, to detect done — an out-of-order early result at index 5 would make length wrong and a value of undefined at index 2 would be missed; and remember a promise settles only once, so a later rejection after the outer promise already resolved is harmless. Know the family: allSettled waits for every promise and never rejects (returns {status,value|reason}[]); race settles as soon as the first promise settles (fulfilled OR rejected); any resolves on the first fulfillment and rejects only if all reject (AggregateError).

Use this technique when

Firing independent requests in parallel and waiting for all. Contrast allSettled (never rejects), race (first settle), any (first fulfill).

References

js