Promise.all() is one of the most-used asynchronous APIs in JavaScript. Below is a quick reference on how to use it, then a mental model of how it works, and finally an interview challenge to implement it from scratch.
Promise.all is used in practicePromise.all() takes an iterable of values (usually Promises) and returns a single Promise. The returned promise fulfills when all input promises fulfill, with an array of the results in the same order as the input. It rejects immediately when any input rejects, with the reason of the first rejection.
The most common use is fetching data from multiple endpoints concurrently before rendering:
const [user, posts, tags] = await Promise.all([fetch('/api/user').then((r) => r.json()),fetch('/api/posts').then((r) => r.json()),fetch('/api/tags').then((r) => r.json()),]);
All three requests start at the same time. The total wait is the duration of the slowest request, not the sum of all three. Other typical use cases:
getUser() and getFeatureFlags() both succeeding before proceeding.If you want partial results when some calls fail (e.g., dashboard widgets where one slow endpoint shouldn't blank the screen), reach for Promise.allSettled instead.
Promise.all works under the hoodA useful one-paragraph mental model before looking at the implementation:
Promise.allwalks the input iterable, attaching a.thenhandler to each value (wrapping non-promise values withPromise.resolvefirst). It tracks completions with a counter and stores results in an array indexed by the original position. When the counter reaches zero, the outer promise fulfills with the results array. The first rejection short-circuits the outer promise; remaining inputs continue running but their results are discarded.
A few specifics worth remembering, since they are commonly mis-stated:
Promise.all([]) resolves synchronously with []. It does not reject.AbortController signal into each request.Implement your own version of Promise.all, called promiseAll, with the difference that the function takes an array instead of a generic iterable. Be sure to read the description carefully and implement accordingly.
// Resolved example.const p0 = Promise.resolve(3);const p1 = 42;const p2 = new Promise((resolve, reject) => {setTimeout(() => {resolve('foo');}, 100);});await promiseAll([p0, p1, p2]); // [3, 42, 'foo']
// Rejection example.const p0 = Promise.resolve(30);const p1 = new Promise((resolve, reject) => {setTimeout(() => {reject('An error occurred!');}, 100);});try {await promiseAll([p0, p1]);} catch (err) {console.log(err); // 'An error occurred!'}
This is a pretty important question to practice because async programming is frequently tested during interviews. Understanding how Promise.all works under the hood will help you in understanding the mechanisms behind similar Promise-related functions like Promise.race,Promise.any, Promise.allSettled, etc.
Approach 1 is the recommended interview answer because it exposes the coordination state directly: one results array for ordered outputs and one counter for how many inputs are still unresolved.
There are a few aspects to this question we need to bear in mind and handle:
Promises are meant to be chained, so the function needs to return a Promise.Promise resolves with an empty array.Promise contains an array of resolved values in the same order as the input if all of them are fulfilled.Promise rejects immediately if any of the input values are rejected or throw an error.Promises.asyncSince the function needs to return a Promise, we can construct a Promise at the top level of the function and return it. The bulk of the code will be written within the constructor parameter.
We first check if the input array is empty, and resolve with an empty array if so.
We then need to attempt resolving every item in the input array. This can be achieved using Array.prototype.forEach or Array.prototype.map. As the returned values will need to preserve the order of the input array, we create a results array and slot the value in the right place using its index within the input array. To know when all the input array values have been resolved, we keep track of how many unresolved promises there are by initializing a counter of unresolved values and decrementing it whenever a value is resolved. When the counter reaches 0, we can return the results array.
One thing to note here is that because the input array can contain non-Promise values, if we are not await-ing them, we need to wrap each value with Promise.resolve() which allows us to use .then() on each of them and we don't have to differentiate between Promise vs non-Promise values and whether they need to be resolved.
Lastly, if any of the values are rejected, we reject the top-level Promise immediately without waiting for any other pending promises.
/*** @param {Array} iterable* @return {Promise<Array>}*/export default function promiseAll(iterable) {return new Promise((resolve, reject) => {// Preserve input order even if the promises settle in a different order.const results = new Array(iterable.length);let unresolved = iterable.length;if (unresolved === 0) {resolve(results);return;}iterable.forEach(async (item, index) => {try {const value = await item;results[index] = value;unresolved -= 1;if (unresolved === 0) {resolve(results);}} catch (err) {reject(err);}});});}
Promise.thenHere's an alternative version which uses Promise.then() if you prefer not to use async/await.
type ReturnValue<T> = { -readonly [P in keyof T]: Awaited<T[P]> };export default function promiseAll<T extends readonly unknown[] | []>(iterable: T,): Promise<ReturnValue<T>> {return new Promise((resolve, reject) => {// Preserve input order even if the promises settle in a different order.const results = new Array(iterable.length);let unresolved = iterable.length;if (unresolved === 0) {resolve(results as ReturnValue<T>);return;}iterable.forEach((item, index) => {// `Promise.resolve()` lets plain values and promises share the same code path.Promise.resolve(item).then((value) => {results[index] = value;unresolved -= 1;if (unresolved === 0) {resolve(results as ReturnValue<T>);}},(reason) => {reject(reason);},);});});}
Once one of the Promise's resolving functions (resolve or reject) is called, the promise is in the "settled" state, and subsequent calls to either function can neither change the fulfillment value or rejection reason nor change the eventual state from "fulfilled" to "rejected" or vice versa.
Promise values, they will still be part of the returned array if all the input values are fulfilled.Promises, how to construct one, how to use them.console.log() statements will appear here.