Promise.any()
ES2021+Returns a promise that fulfills when any of the promises fulfills, or rejects if all of the promises reject.
Syntax
Promise.any(iterable)Parameters
iterable Iterable An iterable of promises
Return Value
A Promise that fulfills with the first fulfilled promise
Examples
Promise.any([
Promise.reject('에러1'),
Promise.resolve('성공!'),
Promise.reject('에러2')
]).then(value => console.log(value)); 📌 When to Use
Use Promise.any() when you need the first successful result from multiple sources, like trying multiple CDNs or mirrors.
⚠️ Common Mistakes
Not handling AggregateError when all promises reject - it contains all rejection reasons.
Using Promise.any() in older browsers without a polyfill (ES2021+ only).
✅ Best Practices
Use for redundancy: try multiple servers and use whichever responds successfully first.
Access all errors on rejection: catch(e => console.log(e.errors)) for AggregateError.
⚡ Performance Notes
Promise.any() is ideal for latency optimization - use the fastest successful response. Consider cancelling remaining requests after the first success.
🌍 Real World Example
Multi-CDN Resource Loader
Load resources from multiple CDNs, using whichever responds first successfully.
async function loadFromCDN(resourcePath) {
const cdns = [
'https://cdn1.example.com',
'https://cdn2.example.com',
'https://cdn3.example.com'
];
const fetchPromises = cdns.map(cdn =>
fetch(`${cdn}${resourcePath}`).then(res => {
if (!res.ok) throw new Error(`${cdn} failed`);
return { cdn, response: res };
})
);
try {
const { cdn, response } = await Promise.any(fetchPromises);
console.log(`Loaded from: ${cdn}`);
return response;
} catch (aggregateError) {
console.error('All CDNs failed:', aggregateError.errors);
throw new Error('Resource unavailable from all CDNs');
}
}
loadFromCDN('/scripts/app.js').then(r => r.text());