Asynchronous JavaScriptLesson 4.4
Promise.all, Promise.race, Promise.allSettled, Promise.any explained
Promise.all, Promise.race, Promise.allSettled, Promise.any, AggregateError, concurrent async patterns, timeout pattern, error handling differences
Running Multiple Promises Concurrently
The four static Promise combinators handle different patterns for running multiple async operations together. Choosing the right one avoids unnecessary serial execution and handles partial failures correctly.
Promise.all — All Must Succeed
const [a, b, c] = await Promise.all([op1(), op2(), op3()]);
// Rejects immediately if ANY operation rejects — fail-fast
Promise.allSettled — Get All Results Regardless
const results = await Promise.allSettled([op1(), op2(), op3()]);
results.forEach(r => {
if (r.status === "fulfilled") console.log(r.value);
else console.error(r.reason);
});
// Never rejects — every result is inspectable
Promise.race — First to Settle Wins
function withTimeout(promise, ms) {
const timeout = new Promise((_, reject) =>
setTimeout(() => reject(new Error("Timeout")), ms)
);
return Promise.race([promise, timeout]);
}
// Resolves or rejects with whichever settles first
Promise.any — First to Succeed Wins
const fastest = await Promise.any([server1(), server2(), server3()]);
// Rejects only if ALL fail, with an AggregateError
Choosing the Right Combinator
Use all when every result is required and one failure should abort the whole operation. Use allSettled for batch jobs where partial failures are acceptable. Use race to implement timeouts or take whichever resource responds first. Use any when you have redundant sources and one success is sufficient.
