Promise.all starts nothing itself: every item is already running. It wraps each with Promise.resolve, writes each result by index so the output keeps the input order, resolves when the count of fulfilled items reaches the total, and rejects with the first rejection. Promise.any is its mirror: the first fulfilment wins, and only if every item rejects does it reject, with an AggregateError. Writing Promise itself shows you understand the rest: three states, settle once, handlers always in a microtask, then returns a new promise resolved with the handler's result, and a returned thenable is adopted one job later.
Implement Promise/Promise-related APIs: Promise, Promise.all, Promise.any
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.
Wrap every item with Promise.resolve so plain values and promises look the same, store each result at its own index, count down, and resolve at zero. Pass reject straight through: the first rejection settles the outer promise and later ones are ignored, because a promise settles only once. An empty array resolves at once.
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
The spec takes any iterable (a Set, a generator), so count while iterating instead of reading length. A non-iterable rejects the returned promise with a TypeError; it never throws. allSettled maps every item to { status, value | reason } and never rejects. any swaps the roles: the first fulfilment resolves, and rejections are collected in input order into an AggregateError, which an empty input produces at once.
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 6 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
- any resolves with the first fulfilment
- any rejects with an AggregateError of every reason, in order
A promise is a small state machine: pending, then fulfilled or rejected, once. then registers a reaction and returns a new promise resolved with whatever the handler returns, or rejected with what it throws; a missing handler passes the value or reason along. Handlers always run in a microtask, even when the promise has already settled. Resolving with a thenable adopts it one job later (NewPromiseResolveThenableJob), which is why returning a promise from then costs two extra ticks. The last check runs the same script on MyPromise and on the native Promise and compares the order.
class MyPromise {#state = 'pending';#value;#reactions = [];constructor(executor) {if (typeof executor !== 'function') throw new TypeError('Promise resolver is not a function');const { resolve, reject } = this.#resolvers();try {executor(resolve, reject);} catch (err) {reject(err); // a throw in the executor rejects}}// A resolve/reject pair where only the first call of either counts.#resolvers() {let called = false;return {resolve: (value) => {if (called) return;called = true;this.#resolve(value);},reject: (reason) => {if (called) return;called = true;this.#settle('rejected', reason);},};}#resolve(value) {if (value === this) return this.#settle('rejected', new TypeError('Chaining cycle detected for promise'));if (value !== null && (typeof value === 'object' || typeof value === 'function')) {let then;try {then = value.then; // read once: a getter may throw or change} catch (err) {return this.#settle('rejected', err);}if (typeof then === 'function') {// Adopt a thenable one job later, like the spec's NewPromiseResolveThenableJob.const { resolve, reject } = this.#resolvers();queueMicrotask(() => {try {then.call(value, resolve, reject);} catch (err) {reject(err);}});return;}}this.#settle('fulfilled', value);}#settle(state, value) {if (this.#state !== 'pending') return;this.#state = state;this.#value = value;for (const reaction of this.#reactions) this.#schedule(reaction);this.#reactions = [];}// Handlers always run in a microtask, never synchronously.#schedule({ onFulfilled, onRejected, resolve, reject }) {queueMicrotask(() => {const fulfilled = this.#state === 'fulfilled';const handler = fulfilled ? onFulfilled : onRejected;if (typeof handler !== 'function') {(fulfilled ? resolve : reject)(this.#value); // pass the value or reason along the chainreturn;}try {resolve(handler(this.#value));} catch (err) {reject(err);}});}then(onFulfilled, onRejected) {return new MyPromise((resolve, reject) => {const reaction = { onFulfilled, onRejected, resolve, reject };if (this.#state === 'pending') this.#reactions.push(reaction);else this.#schedule(reaction);});}catch(onRejected) {return this.then(undefined, onRejected);}finally(onFinally) {return this.then((value) => MyPromise.resolve(onFinally()).then(() => value),(reason) =>MyPromise.resolve(onFinally()).then(() => {throw reason;}),);}static resolve(value) {return value instanceof MyPromise ? value : new MyPromise((resolve) => resolve(value));}static reject(reason) {return new MyPromise((_, reject) => reject(reason));}}
passes 10 checks run on every build, against the native method where there is one
- then runs later, never synchronously
- chains values and catches throws
- a value or reason passes through a then without that handler
- resolves or rejects once only
- a throw in the executor rejects
- adopts thenables and native promises
- resolving with itself is a TypeError
- finally runs either way and keeps the value
- works with await
- schedules in the same order as native Promise
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.
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 }.
First mirror that answers
Fetching the same file from several mirrors or regions and taking whichever succeeds first is Promise.any. It only rejects, with an AggregateError listing every reason, when they all fail.
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.Forgetting that
Promise.all([])resolves at once andPromise.any([])rejects at once.
What is the difference between Promise.all, allSettled, any and race?
all: every item fulfils, or the first rejection. allSettled: waits for every item and reports each outcome, never rejects. any: the first fulfilment, or an AggregateError if all reject. race: the first item to settle either way.
Why does returning a promise from then resolve later than returning a value?
The derived promise has to adopt the returned promise: one job to call its then (NewPromiseResolveThenableJob), one more for that then's reaction. The ordering check in the advanced stage shows the two extra ticks on the native Promise and on ours.
Does Promise.all run the promises in parallel?
It doesn't run anything. The work started when each promise was created; Promise.all only waits. Pass promises that already exist, not functions, and they overlap in time. To limit how many run at once you need a pool that starts work itself.
How would you add a timeout to any promise?
Race it against a timer that rejects: Promise.race([work, new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), ms))]). For fetch, prefer AbortSignal.timeout(ms), which also stops the request.
- tc39.es/ecma262/#sec-promise.all
- tc39.es/ecma262/#sec-promise.allsettled
- tc39.es/ecma262/#sec-promise.any
- tc39.es/ecma262/#sec-promise-resolve-functions
- tc39.es/ecma262/#sec-newpromiseresolvethenablejob
- promisesaplus.com/
- 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
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/any
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError