๐ Implementing a Polyfill for Promise.any in JavaScript

Anmol KansalโขFeb 28, 2025โข2 min readPromise.any is a useful method in JavaScript that takes an array of promises and resolves as soon as any one of them fulfills. If all promises reject, it returns an AggregateError.
Letโs break down how we can implement our own polyfill for Promise.any! ๐ง
๐ง Understanding Promise.any
โ Expected Behavior
- It resolves with the first fulfilled promise.
- If all promises reject, it rejects with an
AggregateError.
๐ Example Usage
const p1 = Promise.reject('Error 1');
const p2 = new Promise((resolve) => setTimeout(() => resolve('Success!'), 1000));
const p3 = Promise.reject('Error 2');
Promise.any([p1, p2, p3]).then(console.log).catch(console.error);
Output:
"Success!" (after 1 second)
If all promises reject:
AggregateError: All promises were rejected
๐ ๏ธ Implementing Promise.any Polyfill
Hereโs how we can implement it:
function promiseAny(promises) {
return new Promise((resolve, reject) => {
let errors = [];
let pending = promises.length;
if (pending === 0) {
return reject(new AggregateError([], 'All promises were rejected'));
}
promises.forEach((promise, index) => {
Promise.resolve(promise)
.then(resolve)
.catch((error) => {
errors[index] = error;
pending--;
if (pending === 0) {
reject(new AggregateError(errors, 'All promises were rejected'));
}
});
});
});
}
It uses Promise.resolve() to handle non-promise values. It resolves on the first success. It Collects errors and rejects only when all promises fail. It mimics the AggregateError behavior.
๐ Usage Example
const p1 = Promise.reject('Error 1');
const p2 = new Promise((resolve) => setTimeout(() => resolve('Success!'), 1000));
const p3 = Promise.reject('Error 2');
promiseAny([p1, p2, p3]).then(console.log).catch(console.error);
๐ Final Thoughts
Implementing polyfills deepens our understanding of JavaScript's built-in functions. Promise.any is particularly useful when you only need the first successful resultโcommon in API failover strategies or parallel task execution.
Let me know if you found this useful! ๐
Table of Contents

Anmol Kansal
Full Stack Developer
I have close to 5 years of industry experience building scalable web interfaces and robust frontend infrastructures. I specialize in React, TypeScript, Next.js, and full-stack JavaScript โ with a strong focus on clean code, performant bundle loading, and highly optimized animation layers.


