Howto Use Promise.any(): When First Success Is Enough
Briefly

Howto 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); } });"
"Gracefully handle modern vs. legacy APIs: const tryClipboard = () => navigator.clipboard.readText().then((txt) => `Clipboard: ${txt}`); const tryPrompt = () => new Promise((resolve, reject) => { const txt = prompt("Paste your data:"); txt === null ? reject(new Error("User canceled input")) : resolve(`Prompt: ${txt}`); }); Promise.any([tryClipboard(), tryPrompt()]) .then((result) => console.log("Got user input:", result)) .catch((err) => { if (err instanceof AggregateError) { console.error("No input methods available:", err.errors); } }); Even if clipboard access fails, the prompt fallback ensures the feature still works. Promise.any([ Promise.reject(new Error("Failure A")), Promise.reject(new Error("Failure B")), ]) .catch((err) => { console.log(err instanceof AggregateErro"
Promise.any settles as soon as any input promise fulfills and ignores individual rejections, rejecting only if every promise fails. The rejection collects all errors in an AggregateError so callers can inspect multiple failure reasons. Use Promise.any to race for the first successful response across mirrors or to prefer modern APIs with legacy fallbacks, improving resiliency and user experience. Handle AggregateError explicitly when all sources fail. Promise.any differs from Promise.all and Promise.race by focusing on the first success rather than waiting for all results or the first completion regardless of outcome.
Read at Substack
Unable to calculate read time
[
|
]