Most people know Promise.all() and Promise.race(), but Promise.any() is the one I’d want when several sources can answer the same question and any good answer will do.
It fulfills with the value of the first input promise that fulfills. Rejections are ignored until one succeeds. That makes it a fit for trying a few mirrors of the same file or a few endpoints for the same data:
const data = await Promise.any([
fetch("https://a.example.com/data.json").then(r => r.json()),
fetch("https://b.example.com/data.json").then(r => r.json()),
]);
Note that fetch() only rejects on network errors, not on a 404 or 500. If you want those to count as failures, throw yourself:
const get = (url) => fetch(url).then(r => {
if (!r.ok) throw new Error(url + " " + r.status);
return r.json();
});
const data = await Promise.any([get(urlA), get(urlB)]);
If every promise rejects, or you pass an empty array, you get an AggregateError. Its errors property lists the reasons in input order:
try {
await Promise.any([get(urlA), get(urlB)]);
} catch (err) {
console.log(err instanceof AggregateError); // true
console.log(err.errors);
}
The difference with Promise.race() is that race settles on the first result of any kind, so one fast failure ends the whole thing. The caveat with any() is that the slower promises are not cancelled. They keep running and the requests still go out, so pair it with an AbortController if the extra traffic matters.
It is supported everywhere since September 2020.
Further reading: MDN: Promise.any()