How do you implement polyfills for Promise.all, Promise.allSettled, Promise.any, and Promise.race from scratch?
In Simple Words:
Promise combinators coordinate multiple concurrent asynchronous operations: Promise.all fails fast on first rejection, Promise.allSettled always waits for all promises to finish, Promise.any returns the first fulfilled promise or an AggregateError, and Promise.race settles as soon as the first promise resolves or rejects.
1. Promise.all Polyfill (Fail-Fast)
Waits for all promises to resolve. Rejects immediately if any promise rejects.
function promiseAll(iterable) {
return new Promise((resolve, reject) => {
const items = Array.from(iterable);
if (items.length === 0) {
return resolve([]);
}
const results = new Array(items.length);
let completed = 0;
items.forEach((item, index) => {
// Wrap in Promise.resolve to handle primitive non-promise values
Promise.resolve(item).then(
(value) => {
results[index] = value; // Preserve original array index order
completed++;
if (completed === items.length) {
resolve(results);
}
},
(error) => {
reject(error); // Fail fast
}
);
});
});
}
2. Promise.allSettled Polyfill (Never Rejects)
Waits until all promises settle (either resolved or rejected) and returns an array of status objects.
function promiseAllSettled(iterable) {
return new Promise((resolve) => {
const items = Array.from(iterable);
if (items.length === 0) {
return resolve([]);
}
const results = new Array(items.length);
let completed = 0;
items.forEach((item, index) => {
Promise.resolve(item)
.then((value) => {
results[index] = { status: 'fulfilled', value };
})
.catch((reason) => {
results[index] = { status: 'rejected', reason };
})
.finally(() => {
completed++;
if (completed === items.length) {
resolve(results);
}
});
});
});
}
3. Promise.any Polyfill (First Fulfillment)
Resolves with the first fulfilled promise value. Rejects only if ALL promises reject, throwing an AggregateError.
function promiseAny(iterable) {
return new Promise((resolve, reject) => {
const items = Array.from(iterable);
if (items.length === 0) {
return reject(new AggregateError([], 'All promises were rejected'));
}
const errors = new Array(items.length);
let rejectedCount = 0;
items.forEach((item, index) => {
Promise.resolve(item).then(
(val) => {
resolve(val); // First fulfillment wins immediately
},
(err) => {
errors[index] = err;
rejectedCount++;
if (rejectedCount === items.length) {
reject(new AggregateError(errors, 'All promises were rejected'));
}
}
);
});
});
}
4. Promise.race Polyfill (First Settled)
Settles as soon as any promise in the iterable settles (either resolved or rejected).
function promiseRace(iterable) {
return new Promise((resolve, reject) => {
const items = Array.from(iterable);
for (const item of items) {
Promise.resolve(item).then(resolve, reject);
}
});
}