Implement Promise.all From Scratch in JavaScript
Implement Promise.all from scratch in JavaScript, keeping result order, handling empty input, iterables, non-promise values and the first rejection. Node.js 24.

Promise.all(iterable) takes a collection of promises and returns one promise. That promise fulfills with an array of all the results, in the original order, when every input fulfills, and rejects with the first rejection as soon as any input rejects. Writing it from scratch is a standard interview task because the short answer hides four details: results must keep input order and not completion order, an empty input resolves at once, values that are not promises count as already fulfilled, and the input can be any iterable and not just an array. This post builds promiseAll on Node.js 24 in stages, with the output of each, and finishes with tests. Its siblings are Promise.race, Promise.allSettled and Promise.any.
What the behavior is
const delay = (value, ms) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
console.log(await Promise.all([delay("slow", 30), delay("fast", 5), 42]));
try {
await Promise.all([delay("ok", 30), Promise.reject(new Error("bad")), delay("also ok", 5)]);
} catch (error) {
console.log(error.message);
}
console.log(await Promise.all([]));[ 'slow', 'fast', 42 ]
bad
[]The first call finishes when the slowest input is done, and the results appear in the order of the inputs, slow first although fast finished earlier. The plain number 42 is accepted and returned as is. The second call rejects with the error of the one failing promise, without waiting for the others. The empty array resolves at once with an empty result. These three lines are the specification to match.
The first version
function promiseAll(promises) {
return new Promise((resolve, reject) => {
const results = [];
let completed = 0;
promises.forEach((promise, index) => {
Promise.resolve(promise).then((value) => {
results[index] = value;
completed += 1;
if (completed === promises.length) {
resolve(results);
}
}, reject);
});
});
}
console.log(await promiseAll([delay("slow", 30), delay("fast", 5), 42]));[ 'slow', 'fast', 42 ]Each input is wrapped with Promise.resolve, which turns plain values and thenables into promises. The result is stored by index, and not with push, so the order is the input order. A counter tracks how many have fulfilled, and when it reaches the length, the outer promise resolves. The rejection handler is the outer reject, so the first rejection wins, and later calls to resolve or reject on a settled promise are ignored.
Using results.push(value) is the classic mistake: it fills the array in completion order, so the output would follow the order in which the inputs finish.
function promiseAllWrong(promises) {
return new Promise((resolve, reject) => {
const results = [];
promises.forEach((promise) => {
Promise.resolve(promise).then((value) => {
results.push(value);
if (results.length === promises.length) {
resolve(results);
}
}, reject);
});
});
}
console.log(await promiseAllWrong([delay("slow", 30), delay("fast", 5), 42]));[ 42, 'fast', 'slow' ]The plain value is ready first, in the next microtask, then fast at 5 ms, then slow at 30 ms. The order shows the bug in one line.
Empty input
With an empty array, forEach runs zero times, so the counter never reaches the length and the promise never settles.
const stuck = promiseAll([]);
const outcome = await Promise.race([stuck, delay("still pending", 20)]);
console.log(outcome);still pendingThe race shows that promiseAll([]) is still pending after 20 ms. The fix is an early return for zero inputs.
function promiseAll2(promises) {
return new Promise((resolve, reject) => {
const items = Array.from(promises);
if (items.length === 0) {
resolve([]);
return;
}
const results = new Array(items.length);
let remaining = items.length;
items.forEach((item, index) => {
Promise.resolve(item).then((value) => {
results[index] = value;
remaining -= 1;
if (remaining === 0) {
resolve(results);
}
}, reject);
});
});
}
console.log(await promiseAll2([]));[]Two changes: the early resolve for an empty input, and a counter that counts down. Array.from(promises) handles the next problem too.
Any iterable
The real Promise.all accepts any iterable, such as a Set or a generator, and does not use .length or .forEach.
function* generate() {
yield delay("g1", 5);
yield "g2";
}
console.log(await Promise.all(new Set([delay("a", 5), "b"])));
console.log(await Promise.all(generate()));
try {
await promiseAll([1, 2].values());
} catch (error) {
console.log(error.name);
}[ 'a', 'b' ]
[ 'g1', 'g2' ]
TypeErrorThe first version fails on an iterator because it calls promises.forEach, which iterators do not have. Using Array.from(promises), as in promiseAll2, takes a snapshot of any iterable. The real function iterates the input lazily, one value at a time, and starts waiting on each as it goes. Taking a snapshot first is simpler and gives the same result for finite iterables.
A non-iterable input, such as a number or undefined, makes the real Promise.all return a rejected promise with a TypeError, and does not throw synchronously. Array.from(5) returns an empty array, so our function would resolve with [] for a number, which is a mismatch to fix if you want the exact behavior.
function promiseAll3(iterable) {
return new Promise((resolve, reject) => {
if (iterable == null || typeof iterable[Symbol.iterator] !== "function") {
reject(new TypeError(`${String(iterable)} is not iterable`));
return;
}
const items = [...iterable];
if (items.length === 0) {
resolve([]);
return;
}
const results = new Array(items.length);
let remaining = items.length;
items.forEach((item, index) => {
Promise.resolve(item).then((value) => {
results[index] = value;
remaining -= 1;
if (remaining === 0) {
resolve(results);
}
}, reject);
});
});
}
try {
await promiseAll3(5);
} catch (error) {
console.log(error.name);
}
console.log(await promiseAll3(new Set([Promise.resolve(1), 2])));TypeError
[ 1, 2 ]A number has no Symbol.iterator, so the returned promise rejects with a TypeError, as the real one does. Throwing inside the executor would reject too, since the executor's exceptions are turned into rejections, but the explicit check makes the intent clear.
Rejection and the other promises
When one input rejects, promiseAll3 rejects, and the other inputs continue to run. Their results are ignored. This matters in practice: Promise.all does not cancel anything. If one of the inputs is a long request, it continues to use the network after the combined promise has failed. If another input later rejects, nobody handles that rejection through the combined promise, but the rejection is not unhandled either, since our then call attached a rejection handler to every input.
const events = [];
const failFast = promiseAll3([
delay("a", 10).then(() => events.push("a done")),
Promise.reject(new Error("early failure")),
]);
await failFast.catch((error) => events.push(error.message));
await delay(null, 20);
console.log(events);[ 'early failure', 'a done' ]The combined promise rejected first, and the slow input finished afterward anyway. To stop outstanding work, pass an AbortSignal to each task, which is outside the scope of Promise.all itself.
Concurrency: all starts everything at once
Promise.all does not control how many tasks run. By the time you call it, all the promises already exist, which means all the work has started. If you map 1,000 URLs to fetch calls and pass the array to Promise.all, you start 1,000 requests together. A concurrency limit needs a different structure: a small pool of workers that take the next task when they finish.
async function mapLimit(items, limit, task) {
const results = new Array(items.length);
let next = 0;
async function worker() {
while (next < items.length) {
const index = next;
next += 1;
results[index] = await task(items[index], index);
}
}
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
return results;
}
let running = 0;
let peak = 0;
const doubled = await mapLimit([1, 2, 3, 4, 5, 6], 2, async (n) => {
running += 1;
peak = Math.max(peak, running);
await delay(null, 5);
running -= 1;
return n * 2;
});
console.log(doubled, peak);[ 2, 4, 6, 8, 10, 12 ] 2Two workers each take one item at a time, so at most two tasks run at once, and peak records that. The results still come back in input order. It uses Promise.all only to wait for the workers.
Errors, handlers and unhandled rejections
One detail separates a correct implementation from a risky one: every input promise needs a rejection handler attached, even after the combined promise has already rejected. If you only attach the handler to the first failing promise, a later rejection in another input has no handler and Node.js reports an unhandled rejection, which ends the process by default since version 15. The implementation above attaches reject as the second argument of then for every item, so every rejection is observed. After the first one, the calls to reject do nothing, which is the intended effect.
That is also why you should not write Promise.all as a loop of await. A loop awaits the items one at a time, so a later promise that rejects while an earlier one is still pending has no handler yet. In Node.js 24 that can crash the process even though the code looks safe. Start all the work first, collect the promises, and pass them to Promise.all in the same synchronous step.
A last point is about what the rejection reason is. Promise.all rejects with the reason of the first input to reject in time, which is not always the first one in the array. If two inputs fail, the earlier failure wins and the other is silently ignored. When you need every error, use Promise.allSettled and inspect the results.
Tests
import test from "node:test";
import assert from "node:assert/strict";
test("promiseAll keeps input order", async () => {
const result = await promiseAll3([delay("slow", 20), delay("fast", 1), 3]);
assert.deepEqual(result, ["slow", "fast", 3]);
});
test("promiseAll rejects with the first rejection", async () => {
await assert.rejects(promiseAll3([delay(1, 20), Promise.reject(new Error("no"))]), /no/);
});
test("promiseAll resolves an empty input", async () => {
assert.deepEqual(await promiseAll3([]), []);
});ℹ tests 3
ℹ pass 3
ℹ fail 0How to present it
Describe the contract in one breath: all fulfill, in order, or the first rejection. Write the short version using Promise.resolve and an indexed array. Then raise the details yourself: the empty input, the order of results and the iterable argument. If the interviewer asks how it differs from allSettled, say that all fails fast, and allSettled never rejects and reports each outcome. If they ask about limits, describe the worker pool.


