Promise.race and .any
Promise.race resolves/rejects with the first settled promise. Promise.any resolves with the first fulfilled promise, ignoring rejections.
Promise.race resolves/rejects with the first settled promise. Promise.any resolves with the first fulfilled promise, ignoring rejections.
// Timeout pattern
const timeout = ms => new Promise((_, r) => setTimeout(() => r(new Error("Timeout")), ms));
const result = await Promise.race([fetch("/api/data"), timeout(3000)]);
// First successful CDN
const img = await Promise.any([fetchFrom("cdn1"), fetchFrom("cdn2"), fetchFrom("cdn3")]);
Promise.race for timeouts; Promise.any for fallback/redundancy patterns.
More in JavaScript