fromSubstack
1 week agoHowto Use Promise.any(): When First Success Is Enough
It resolves as soon as one promise fulfills, ignoring failures (unless all fail). This makes it a powerful tool for resilient and user-friendly async workflows. Suppose you have multiple mirror servers and only need the first working one: const fetchWithCheck = (url) => fetch(url).then((res) => { if (!res.ok) throw new Error(`HTTP error: ${res.status}`); return res; }); Promise.any([ fetchWithCheck("https://mirror1.example.com/data"), fetchWithCheck("https://mirror2.example.com/data"), fetchWithCheck("https://mirror3.example.com/data"), ]) .then((res) => res.json()) .then((data) => console.log("First available data:", data)) .catch((err) => { if (err instanceof AggregateError) { console.error("All servers failed:", err.errors); } else { console.error("Unexpected error:", err); } });
Software development