Combining Promise.all and Promise.race
You'll learn how to mix Promise.all and Promise.race to create sophisticated control flow patterns for complex async scenarios.
Now that you know both Promise.all and Promise.race, you can combine them to handle advanced use cases. These patterns let you orchestrate multiple groups of promises with different settling strategies.
Racing Multiple Groups
You can race groups of promises where each group waits for all its members:
const group1 = Promise.all([fetch('/api/v1/data'), fetch('/api/v1/meta')]);
const group2 = Promise.all([fetch('/api/v2/data'), fetch('/api/v2/meta')]);
Promise.race([group1, group2])
.then(winner => console.log('Fastest API version won:', winner));
Whichever API version completes both requests first wins the race.
Timeout Pattern for Promise.all
Add a timeout to an entire Promise.all operation:
const allTasks = Promise.all([
slowTask1(),
slowTask2(),
slowTask3()
]);
const timeout = new Promise((_, reject) =>
setTimeout(() => reject(new Error('Timeout')), 5000)
);
Promise.race([allTasks, timeout])
.then(results => console.log('All completed:', results))
.catch(err => console.log('Failed or timed out:', err.message));
If all tasks don't complete within 5 seconds, the timeout wins and rejects.
Partial Success with Timeouts
You might race individual promises with timeouts, then use Promise.all to collect results:
const withTimeout = (promise, ms) =>
Promise.race([promise, new Promise((_, reject) =>
setTimeout(() => reject(new Error('Timeout')), ms))]);
Promise.all([
withTimeout(task1(), 1000),
withTimeout(task2(), 1000),
withTimeout(task3(), 1000)
]).catch(err => console.log('At least one timed out'));
Key Takeaway: Combining Promise.all and Promise.race enables patterns like racing groups, adding timeouts to parallel operations, or creating fallback strategies for complex async workflows.