Promise Combinators: Real-World Examples in JavaScript
Real-world examples of Promise.all, allSettled, race, and any in actual applications.
Promise Combinators: Real-World Examples in JavaScript
Promise combinators are used in real applications. Here are practical examples.
1. Loading Multiple Resources (Promise.all)
async function loadPage(userId) { const [user, posts, friends] = await Promise.all([ fetch(`/api/users/${userId}`).then((r) => r.json()), fetch(`/api/users/${userId}/posts`).then((r) => r.json()), fetch(`/api/users/${userId}/friends`).then((r) => r.json()), ]); return { user, posts, friends }; } `` ### 2. Best-Effort Data Fetching (Promise.allSettled) ```js async function loadDashboard(userId) { const results = await Promise.allSettled([ fetchNotifications(userId), fetchRecommendations(userId), fetchTrending(), ]); return { notifications: results[0].status === "fulfilled" ? results[0].value : [], recommendations: results[1].status === "fulfilled" ? results[1].value : [], trending: results[2].status === "fulfilled" ? results[2].value : [], }; } `` Some widgets may fail, but the dashboard still loads with available data. ### 3. Timeout for API Calls (Promise.race) ```js async function fetchWithTimeout(url, ms) { return Promise.race([ fetch(url), new Promise((_, reject) => setTimeout(() => reject(new Error("timeout")), ms)), ]); } `` ### 4. First Successful Mirror (Promise.any) ```js async function fetchFromMirrors(path) { return Promise.any([ fetch(`https://mirror1.example.com${path}`), fetch(`https://mirror2.example.com${path}`), fetch(`https://mirror3.example.com${path}`), ]); } `` Try multiple mirrors; use whichever responds first. ### 5. Batch Processing with Limit ```js async function processBatch(items, batchSize, processFn) { for (let i = 0; i < items.length; i += batchSize) { await Promise.all( items.slice(i, i + batchSize).map(processFn) ); } } `` Process `batchSize` items at a time to avoid overwhelming the server. ### 6. Polling Until Success (Promise.any pattern) ```js async function pollUntilReady(url, maxAttempts, delay) { for (let i = 0; i < maxAttempts; i++) { try { const res = await fetch(url); if (res.ok) return await res.json(); } catch {} await new Promise((resolve) => setTimeout(resolve, delay)); } throw new Error("Polling failed"); } `` ### The Takeaway Real-world examples: `Promise.all` for loading multiple resources, `allSettled` for best-effort dashboards, `race` for timeouts, `any` for first successful mirror, batching with `Promise.all` and limits, and polling. Each combinator has a specific real-world use case.
Loading multiple resources in parallel (user, posts, friends), fetching multiple pages, parallel data transformation, and batch processing with limits. Any scenario where you need all results and any failure is a total failure.
Best-effort data fetching (dashboard widgets that may fail individually), partial success scenarios, and when you want all results regardless of failures. Some widgets fail, but the page still loads with available data.
Timeouts (race an operation against a timeout promise), first successful source (whichever responds first), and cancellation patterns. Common for API calls that should not hang forever.
Fetching from multiple mirrors (use whichever responds first), fallback APIs (try multiple, use first success), and redundant data sources. If all fail, you get an AggregateError with all reasons.
Process batchSize items at a time with Promise.all: for (let i = 0; i < items.length; i += batchSize) { await Promise.all(items.slice(i, i + batchSize).map(processFn)); }. This avoids overwhelming the server.
Ready to master React completely?
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.
Master React
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course.

