Return a new promise. Wrap every item in Promise.resolve, write each result at its index so the output order matches the input, count fulfilments, and resolve when the count reaches the total; pass reject straight through so the first rejection wins. Handle an empty input (resolve [] at once) and any iterable, and remember Promise.all only waits: the work is already running. The common follow-up is a version that limits concurrency, which has to take functions so it can decide when each task starts.
Implement Promise.all.
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
Every item goes through Promise.resolve, each result lands at its own index, and the promise resolves when the last one arrives. reject is passed straight through, so the first rejection settles the result and later ones are ignored.
function promiseAll(items) {return new Promise((resolve, reject) => {const results = [];let remaining = items.length;if (remaining === 0) {resolve(results);return;}items.forEach((item, i) => {// Promise.resolve turns plain values and other promises into one shape.Promise.resolve(item).then((value) => {results[i] = value; // by index: results keep the input orderremaining -= 1;if (remaining === 0) resolve(results);}, reject); // the first rejection rejects the whole thing});});}
passes 5 checks run on every build, against the native method where there is one
- resolves with every value, in input order
- rejects with the first rejection
- an empty list resolves to []
- plain values pass through
- agrees with native Promise.all
Any iterable works (count while iterating; generators have no length), a non-iterable rejects with a TypeError instead of throwing, and thenables are adopted. allSettled and any come almost free from the same loop.
function promiseAll(iterable) {return new Promise((resolve, reject) => {const results = [];let count = 0;let fulfilled = 0;try {// Any iterable: arrays, Sets, generators. A non-iterable throws here.for (const item of iterable) {const i = count++;Promise.resolve(item).then((value) => {results[i] = value;if (++fulfilled === count) resolve(results);}, reject);}} catch (err) {reject(err); // returns a rejected promise, it never throwsreturn;}// Callbacks run later, so count is final before any of them fires.if (count === 0) resolve(results);});}function promiseAllSettled(iterable) {return promiseAll(Array.from(iterable, (item) =>Promise.resolve(item).then((value) => ({ status: 'fulfilled', value }),(reason) => ({ status: 'rejected', reason }),),),);}function promiseAny(iterable) {return new Promise((resolve, reject) => {const errors = [];let count = 0;let rejected = 0;try {for (const item of iterable) {const i = count++;Promise.resolve(item).then(resolve, (reason) => {errors[i] = reason;if (++rejected === count) reject(new AggregateError(errors, 'All promises were rejected'));});}} catch (err) {reject(err);return;}if (count === 0) reject(new AggregateError(errors, 'All promises were rejected'));});}
passes 4 checks run on every build, against the native method where there is one
- takes any iterable: a Set and a generator
- a non-iterable gives a rejected promise, not a throw
- adopts thenables, like native
- allSettled reports every outcome
Uploading 500 files with Promise.all(files.map(upload)) opens 500 requests at once. A pool takes functions, not promises, so nothing starts until a slot is free: start limit tasks, and each time one finishes, start the next. Results still go by index, a failure rejects and stops new starts, and a task that throws synchronously is caught because it runs inside a then. This is what libraries like p-limit do.
// Runs async tasks with at most `limit` in flight; results keep the input order.function promiseAllLimit(tasks, limit) {if (!Number.isInteger(limit) || limit < 1) throw new RangeError('limit must be a whole number from 1');return new Promise((resolve, reject) => {const results = new Array(tasks.length);let next = 0;let running = 0;let done = 0;let failed = false;if (tasks.length === 0) {resolve(results);return;}const startNext = () => {// Fill free slots; a task is a function, so nothing starts before its turn.while (!failed && running < limit && next < tasks.length) {const i = next++;running++;Promise.resolve().then(() => tasks[i]()).then((value) => {results[i] = value;running--;done++;if (done === tasks.length) resolve(results);else startNext();},(err) => {failed = true; // no new tasks start after a failurereject(err);},);}};startNext();});}
passes 5 checks run on every build, against the native method where there is one
- never runs more than the limit at once
- starts the next task as soon as a slot frees
- rejects on the first failure and starts nothing new
- a task that throws synchronously rejects
- empty input resolves to [] and a bad limit throws
Loading a page's data in parallel
A dashboard that needs the user, their projects and their notifications fires all three fetches and waits once: const [user, projects, inbox] = await Promise.all([getUser(), getProjects(), getInbox()]). Awaiting them one by one, which agents often write inside a for loop, takes the sum of the three times instead of the longest.
Uploads and API rate limits
Firing hundreds of requests at once trips rate limits and saturates the connection. Concurrency pools like p-limit keep a fixed number in flight, the same algorithm as the advanced stage.
One failing widget shouldn't blank the page
Promise.all rejects as soon as one request fails, and the others' results are lost. For independent widgets use Promise.allSettled and render each one from its own { status, value | reason }.
awaitinside aforloop over independent requests: they run one after another, not in parallel.Assuming
Promise.allcancels the rest when one fails: the other requests keep running, only their results are ignored.Pushing results in completion order (
results.push(value)) instead of writing by index: the output order then depends on timing.Resolving on
count === items.lengthwhen the input is a generator, which has nolength.Calling a
thenhandler synchronously when the promise is already settled: handlers always run in a microtask.Passing promises to a concurrency limiter: they have all started already, so the limit does nothing. Pass functions that create them.
Why must the concurrency-limited version take functions?
A promise represents work that has already started. Only a function lets the pool decide when the work begins.
How is Promise.all different from awaiting in a loop?
for (const id of ids) results.push(await get(id)) waits for each request before starting the next, so the total time is the sum. Promise.all(ids.map(get)) starts them all first and waits once, so the total is the slowest.
What happens to the other promises when one rejects?
Nothing: they keep running and their results are dropped. To actually stop the requests, pass one AbortController's signal to each fetch and abort it in the rejection handler.
- tc39.es/ecma262/#sec-promise.all
- tc39.es/ecma262/#sec-promise.allsettled
- tc39.es/ecma262/#sec-newpromiseresolvethenablejob
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled
- github.com/sindresorhus/p-limit