Welcome back. In our last lesson, we deconstructed async/await, revealing it as a sophisticated layer of syntactic sugar over generators and the microtask queue. You now understand that await provides a non-blocking "pause," making sequential asynchronous logic clean and readable.
However, senior-level engineering isn't just about writing clean code; it's about writing performant and resilient code. The default sequential nature of await can become a bottleneck. What if you need to fire off multiple independent API requests simultaneously? Waiting for each one to finish before starting the next is inefficient and leads to a sluggish user experience.
This is where Promise combinators come in. They are the built-in JavaScript toolkit for managing concurrent asynchronous operations. In this lesson, we will dissect the four key combinators: Promise.all, Promise.allSettled, Promise.race, and Promise.any. Mastering their distinct behaviors will enable you to select the precise tool for any given scenario, a critical skill for building robust, high-performance systems and a frequent topic in senior engineering interviews.
An Overview of the Promise Combinators
Before we dive into each method, let's get a high-level overview. The following video provides an excellent introduction to these four APIs, explaining the core problem they solve and setting the stage for our deep dive.
Promise APIs + Interview Questions 🔥 | S.02 Ep.05 - Namaste JavaScript | all, allSettled, race, any
This video from the "Namaste JavaScript" series offers a clear, theoretical foundation for the four main Promise APIs. It uses helpful diagrams to build a mental model for each one.
To start, watch the introduction from the beginning to understand why these APIs are important. Then, watch the quick revision at the end, which summarizes the behavior of all four. Don't worry about understanding every detail in the summary yet; we'll break each one down next. Pay close attention to the terminology used: settled, fulfilled, and rejected.
As you saw, all four combinators take an iterable of Promises (usually an array) and return a single new Promise. The difference lies in how that single Promise behaves based on the outcomes of the input Promises.
1. Promise.all - The All-or-Nothing Strategy [Always asked]
Promise.all is the most common combinator. It's your tool for when a set of asynchronous operations are all-or-nothing; you need every single one to succeed.
Think about loading a user's dashboard. You might need their profile information, their list of recent orders, and their notification settings. If any of these critical API calls fail, the dashboard is incomplete and cannot be properly rendered. A single failure should invalidate the entire operation. This is the exact use case for Promise.all.
Let's watch the detailed explanation of its behavior.
Promise APIs + Interview Questions 🔥 | S.02 Ep.05 - Namaste JavaScript | all, allSettled, race, any
This segment explains the "fail-fast" nature of Promise.all and demonstrates its behavior with both success and failure cases.
Watch the theoretical explanation from the start of the Promise.all section. Then, watch the corresponding code demo to see it in action.
Key Behavior of Promise.all:
- Input: An array of Promises.
- Success: It resolves only when all input Promises have resolved. The resolved value is an array containing the resolution values of the input Promises, in the same order they were passed in.
- Failure: It rejects as soon as any one of the input Promises rejects. The rejection reason is the reason from that first-rejected Promise. It does not wait for the other Promises to finish. This is called "fail-fast" behavior.
Here is a practical example of loading the dashboard data we discussed.
JS await Multiple Promises: Unlock Next-Level Concurrency (2024) & Conquer Async Challenges!
The examples in this article use modern async/await syntax, which will help connect the theory to your daily work.
First, read the section on Promise.all for a clear definition. Then, examine the practical example in the section "Concurrent API Calls". Notice how three independent fetch promises are created first, then passed to Promise.all. This ensures they all run in parallel.
// A practical example of Promise.all
async function loadDashboardData(userId) {
try {
// All three fetch requests are initiated concurrently
const [userData, ordersData, productsData] = await Promise.all([
fetch(`/api/users/${userId}`),
fetch(`/api/users/${userId}/orders`),
fetch(`/api/users/${userId}/products/favorites`)
]);
// This block is only reached if all three fetches succeed
const user = await userData.json();
const orders = await ordersData.json();
const products = await productsData.json();
console.log('All data loaded:', { user, orders, products });
// ... render dashboard
} catch (error) {
// This block is executed if ANY of the fetches fail
console.error('Failed to load dashboard data:', error);
// ... render an error state
}
}
This pattern is fundamental for performance. Instead of awaiting each fetch sequentially, you run them in parallel. The total wait time is determined by the slowest single request, not the sum of all requests.
2. Promise.allSettled - The Auditor [Often asked]
What if your operations aren't all-or-nothing? Imagine you're loading a product page. The product details are critical, but the user reviews are optional. If the reviews API fails, you should still render the rest of the page. You just want a report of what succeeded and what failed. For this, you need Promise.allSettled.
Promise APIs + Interview Questions 🔥 | S.02 Ep.05 - Namaste JavaScript | all, allSettled, race, any
This part of the video contrasts allSettled with all, emphasizing that it waits for all promises to finish, regardless of their outcome.
Watch the theoretical explanation from this timestamp. Then, see the practical demonstration from the code demo.
Key Behavior of Promise.allSettled:
- Input: An array of Promises.
- Success: It always resolves (it never rejects itself unless there's a programming error). It waits for all input Promises to settle (either resolve or reject).
- Resolved Value: The resolved value is an array of objects, each describing the outcome of the corresponding input Promise. Each object has:
- A
statusproperty: either'fulfilled'or'rejected'. - If fulfilled, a
valueproperty with the resolution value. - If rejected, a
reasonproperty with the rejection reason.
- A
Let's look at a code example where some data is critical and some is not.
JS await Multiple Promises: Unlock Next-Level Concurrency (2024) & Conquer Async Challenges!
We'll refer back to the same article for a practical implementation.
Read the definition under Promise.allSettled(), then study the code in the section "Handling Optional Data Fetches". This demonstrates how to process the array of result objects.
// A practical example of Promise.allSettled
async function loadPageWithOptionalContent() {
const results = await Promise.allSettled([
fetch('/api/products/main-details'), // Critical
fetch('/api/products/reviews'), // Optional
fetch('/api/promotions/banner') // Optional
]);
const detailsResult = results[0];
const reviewsResult = results[1];
if (detailsResult.status === 'fulfilled') {
const details = await detailsResult.value.json();
// Render main component
} else {
// Render error state for the whole page
console.error("Critical data failed to load:", detailsResult.reason);
return;
}
if (reviewsResult.status === 'fulfilled') {
const reviews = await reviewsResult.value.json();
// Render reviews section
} else {
// Silently log the error or show a "reviews unavailable" message
console.warn("Reviews failed to load:", reviewsResult.reason);
}
}
Promise.allSettled is the safest combinator. It guarantees you won't lose the results of successful operations just because one of their siblings failed.
3. Promise.race - The First to Finish [Often asked]
As the name implies, Promise.race is for competitive scenarios. It returns the outcome of the very first promise that settles, whether it's a success or a failure. The rest are ignored.
The most common use case is implementing a timeout for an asynchronous operation. You "race" your actual operation against a promise that rejects after a certain duration.
Promise APIs + Interview Questions 🔥 | S.02 Ep.05 - Namaste JavaScript | all, allSettled, race, any
This segment explains that Promise.race concludes with the very first settled promise.
Watch the theory from this timestamp, followed by the code demo. Notice how the result is the value itself, not an array.
Key Behavior of Promise.race:
- Input: An array of Promises.
- Outcome: It settles (resolves or rejects) as soon as the first input Promise settles. The final promise mirrors the outcome of that winning promise exactly.
Here is the classic timeout implementation.
JS await Multiple Promises: Unlock Next-Level Concurrency (2024) & Conquer Async Challenges!
The timeout pattern is a must-know for interviews.
Read the definition under Promise.race(). Then, study the timeout example. This is a very common and powerful pattern.
// A practical example of Promise.race for timeouts
function createTimeout(ms) {
return new Promise((_, reject) =>
setTimeout(() => reject(new Error(`Operation timed out after ${ms}ms`)), ms)
);
}
async function fetchWithTimeout(url, timeoutMs) {
try {
const response = await Promise.race([
fetch(url),
createTimeout(timeoutMs)
]);
const data = await response.json();
console.log('Data fetched successfully:', data);
} catch (error) {
console.error('Fetch failed or timed out:', error.message);
}
}
fetchWithTimeout('https://api.example.com/slow_endpoint', 2000);
If fetch(url) takes more than 2 seconds, the createTimeout promise will reject first, causing the Promise.race to reject, and the catch block will execute.
4. Promise.any - The First to Succeed [Occasionally asked]
Promise.any is similar to Promise.race, but with a key difference: it's looking for the first promise to be fulfilled (successful). It will ignore any promises that reject, hoping that another one will eventually succeed.
This is perfect for scenarios with redundant data sources, like fetching a critical asset from multiple CDNs. You don't care which CDN responds, as long as one of them does.
Promise APIs + Interview Questions 🔥 | S.02 Ep.05 - Namaste JavaScript | all, allSettled, race, any
This final segment explains how Promise.any seeks the first success and introduces the unique AggregateError.
Watch the theory explanation from this timestamp. Then, see it demonstrated in the code example, paying close attention to how AggregateError is handled.
Key Behavior of Promise.any:
- Input: An array of Promises.
- Success: It resolves as soon as the first input Promise resolves. The resolved value is the value of that first successful promise.
- Failure: It only rejects if all of the input Promises reject. The rejection reason is a special
AggregateErrorobject, which holds an array of all the individual rejection reasons.
Here is an example of fetching a resource from multiple locations.
JS await Multiple Promises: Unlock Next-Level Concurrency (2024) & Conquer Async Challenges!
This example shows how Promise.any builds resiliency.
Read the definition under Promise.any(), and then review the code in the "Fetching from Multiple Sources" section.
// A practical example of Promise.any for redundancy
async function getFastestSuccessfulImage(imageName) {
try {
const imageBlob = await Promise.any([
fetch(`https://cdn1.example.com/${imageName}`).then(r => r.ok ? r.blob() : Promise.reject('CDN1 Failed')),
fetch(`https://cdn2.example.com/${imageName}`).then(r => r.ok ? r.blob() : Promise.reject('CDN2 Failed')),
fetch(`/local_fallback/${imageName}`).then(r => r.ok ? r.blob() : Promise.reject('Local Failed'))
]);
// Display the image
const objectURL = URL.createObjectURL(imageBlob);
document.querySelector('#my-image').src = objectURL;
} catch (error) {
// This block only runs if ALL sources fail
if (error instanceof AggregateError) {
console.error("All image sources failed to load.");
// error.errors will be ['CDN1 Failed', 'CDN2 Failed', 'Local Failed']
console.log(error.errors);
}
}
}
Mental Model: A Visual Summary
To solidify these concepts, here are two excellent visual aids that summarize the differences between the four combinators.


A Decision-Making Framework
When faced with a concurrency problem, use this simple mental checklist to choose the right combinator:
-
Do I need the outcome of every single operation, regardless of success or failure?
- Yes? Use
Promise.allSettled(). You're an auditor who needs a complete report.
- Yes? Use
-
Is a single failure a total failure for the entire group of operations?
- Yes? Use
Promise.all(). You're building something where all parts are critical.
- Yes? Use
-
Do I only care about whichever operation finishes first, success or failure?
- Yes? Use
Promise.race(). You're in a competition and only the first finisher matters (e.g., a timeout).
- Yes? Use
-
Do I just need one successful operation out of many, and I can ignore any failures?
- Yes? Use
Promise.any(). You're building for redundancy and just need one source to come through.
- Yes? Use
Conclusion
You have now analyzed the four essential Promise combinators. You understand not just what they do, but why and when to use them. This knowledge is not academic; it directly translates to writing more performant, resilient, and responsive applications. In a senior interview, being able to articulate the trade-offs between Promise.all and Promise.allSettled, or explain the timeout pattern with Promise.race, demonstrates a deep command of asynchronous JavaScript.
Key Takeaways:
Promise.all: All or nothing. Fails fast. Use for critical, interdependent tasks.Promise.allSettled: Get all outcomes. Never rejects. Use for independent tasks where partial failure is acceptable.Promise.race: First to settle wins. Mirrors the first promise to finish (resolve or reject). Use for timeouts or fastest-response scenarios.Promise.any: First to succeed wins. Ignores rejections unless all fail. Use for redundancy and fallbacks.
In our next lesson, we will build on this foundation by diving deeper into asynchronous error handling. You've seen how these combinators reject, but we'll explore how to create custom Error subclasses for more expressive error states and how to catch unhandled promise rejections at a global level to prevent your application from silently failing.