SyntaxStudy
Sign Up
JavaScript Promise.race and Promise.any
JavaScript Intermediate 4 min read

Promise.race and Promise.any

Promise.race and .any

Promise.race resolves/rejects with the first settled promise. Promise.any resolves with the first fulfilled promise, ignoring rejections.

Example
// 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")]);
Pro Tip

Promise.race for timeouts; Promise.any for fallback/redundancy patterns.