brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Promise.any() takes the first promise that succeeds and ignores failures

Web-Development
~/tips/tip-javascript-promise-any

const data = await Promise.any([

Resolves with the first promise that succeeds and only fails when all of them fail.

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()

More Web-Development tips ab -n 200 -c 10 https://example.com/ console.assert(items.length > 0, 'cart is empty', items) document.designMode = "on" function save(item) { Save draft All Web-Development tips (67) All topics

Link