
If you've been working with JavaScript or Node.js for a while, you've probably used promises to handle asynchronous operations. Whether you're fetching data from an API, querying a database, or reading files, promises make it easier to work with operations that don't finish immediately.
But there's one situation that comes up quite often in real projects: what if you need to handle multiple promises at the same time?
For example, imagine you're building an admin dashboard using Node.js. The dashboard needs to fetch user information, recent orders, and product statistics from different APIs. You could wait for each request separately, but that might increase the total response time.
JavaScript provides four useful methods for handling multiple promises: Promise.all(), Promise.allSettled(), Promise.race(), and Promise.any().
At first, these methods can look almost identical because they all accept an iterable of promises. However, each one behaves differently when promises succeed, fail, or finish at different times.
Understanding these differences will help you write better asynchronous code and avoid common bugs in your Node.js applications.
Let's look at each method with practical examples.
What Are Promise Combinators in JavaScript?
Before comparing these four methods, let's quickly understand what they do.
A promise represents the eventual success or failure of an asynchronous operation. It can be in one of three states:
Pending: The operation hasn't settled yet.
Fulfilled: The operation completed successfully.
Rejected: The operation failed.
JavaScript provides several static methods on the Promise object that help you coordinate multiple promises.
Here's a quick overview:
Method | When does the returned promise fulfill? | What happens when promises reject? |
|---|---|---|
| When every input fulfills | Rejects when an input rejects |
| When every input settles | Individual rejections are included in the results |
| When the first input settles | Rejects if the first settled input rejects |
| When the first input fulfills | Rejects with an |
The most important difference is what each method considers a successful outcome.
Let's explore them one by one.
1. What Is Promise.all() in JavaScript?
Promise.all() is used when you have multiple promises and need every operation to succeed before continuing.
It takes an iterable of promises or other values and returns a promise that fulfills when all the inputs fulfill.
If any input promise rejects, the returned promise rejects with that rejection reason.
Let's start with a simple example.
const promise1 = Promise.resolve("User fetched");
const promise2 = Promise.resolve("Orders fetched");
const promise3 = Promise.resolve("Products fetched");
Promise.all([promise1, promise2, promise3])
.then((results) => {
console.log(results);
})
.catch((error) => {
console.error(error);
});Output:
[
'User fetched',
'Orders fetched',
'Products fetched'
]All three promises fulfilled, so Promise.all() returned their results in an array.
One useful detail is that the result order matches the input order, not the order in which the promises finish.
For example, if the third promise finishes first and the first promise finishes last, the results will still appear in the same order as the original array.
Using Promise.all() With async/await
In modern Node.js applications, you will often see Promise.all() used with async/await.
async function fetchDashboardData() {
try {
const [user, orders, products] = await Promise.all([
getUser(),
getOrders(),
getProducts()
]);
return {
user,
orders,
products
};
} catch (error) {
console.error("Unable to fetch dashboard data:", error);
throw error;
}
}Here, all three functions are called before execution waits for the combined promise.
Assuming these operations are independent, they can proceed concurrently instead of waiting for one another.
This can reduce the total time needed to fetch the dashboard data.
What Happens If One Promise Fails?
Consider this example:
const promise1 = Promise.resolve("User fetched");
const promise2 = Promise.reject(new Error("Orders API failed"));
const promise3 = Promise.resolve("Products fetched");
Promise.all([promise1, promise2, promise3])
.then((results) => {
console.log(results);
})
.catch((error) => {
console.log(error.message);
});Output:
Orders API failedEven though two promises fulfilled, the combined promise rejected because one input rejected.
This is known as fail-fast behavior.
However, there's an important distinction: Promise.all() does not cancel the other operations when one promise rejects. They may continue running in the background.
When Should You Use Promise.all()?
Use Promise.all() when all results are required to complete a task successfully.
For example:
Fetching multiple independent resources for a dashboard.
Loading configuration files required to start an application.
Running independent database queries before generating a report.
Fetching product details and related information for a page.
If one result is essential and its operation fails, it may make sense for the whole operation to fail.
However, if you want to collect successful results even when some operations fail, another method might be a better choice.
2. What Is Promise.allSettled() in JavaScript?
Promise.allSettled() is useful when you want to know the outcome of every promise, regardless of whether it succeeds or fails.
Unlike Promise.all(), it doesn't reject just because one input promise rejects.
Instead, it waits until all input promises have settled.
Remember that a promise is settled when it becomes either fulfilled or rejected.
Let's look at an example.
const promise1 = Promise.resolve("Email sent");
const promise2 = Promise.reject(new Error("SMS failed"));
const promise3 = Promise.resolve("Notification saved");
Promise.allSettled([promise1, promise2, promise3])
.then((results) => {
console.log(results);
});Output:
[
{
status: "fulfilled",
value: "Email sent"
},
{
status: "rejected",
reason: Error: SMS failed
},
{
status: "fulfilled",
value: "Notification saved"
}
]The exact console formatting of the error may differ between environments, but the result structure remains the same.
Notice that the returned promise fulfills after all three input promises settle.
The rejected promise appears in the results with a status of "rejected" and its rejection reason.
The other two promises still appear as fulfilled results.
Using Promise.allSettled() With async/await
Let's say you're building a notification system that sends messages through email, SMS, and push notifications.
Suppose the SMS provider is temporarily unavailable. You might still want to know whether the email and push notifications succeeded.
Here's how you could handle that:
async function sendNotifications(user) {
const results = await Promise.allSettled([
sendEmail(user.email),
sendSMS(user.phone),
sendPushNotification(user.id)
]);
results.forEach((result, index) => {
if (result.status === "fulfilled") {
console.log(`Task ${index + 1} succeeded`);
} else {
console.error(
`Task ${index + 1} failed:`,
result.reason
);
}
});
return results;
}This approach allows you to inspect every outcome instead of stopping at the first failure.
In a real application, you would probably use meaningful task names rather than relying on array indexes.
When Should You Use Promise.allSettled()?
Use Promise.allSettled() when every result matters, including failures.
Common examples include:
Sending notifications through multiple services.
Processing several independent files.
Running background jobs where each job should be reported separately.
Collecting results from multiple third-party APIs.
Performing cleanup tasks where you need to know which operations succeeded.
For example, if you're processing 100 independent records, you may want to know which records were successfully processed and which ones failed.
Promise.allSettled() makes that easier because every result is returned in the corresponding input position.
One thing to remember is that it waits for every input to settle. If one promise never settles, the combined promise also remains pending.
3. What Is Promise.race() in JavaScript?
Promise.race() returns a promise that settles as soon as the first input promise settles.
That means the first promise to fulfill or reject determines the outcome.
Unlike Promise.any(), Promise.race() doesn't specifically look for successful results.
Let's see how it works.
const promise1 = new Promise((resolve) => {
setTimeout(() => resolve("Task 1 completed"), 2000);
});
const promise2 = new Promise((resolve) => {
setTimeout(() => resolve("Task 2 completed"), 1000);
});
Promise.race([promise1, promise2])
.then((result) => {
console.log(result);
});Output:
Task 2 completedThe second promise fulfills after approximately one second, while the first takes approximately two seconds.
Since the second promise settles first, Promise.race() fulfills with its value.
What If the First Promise Rejects?
This is where Promise.race() differs from Promise.any().
Consider this example:
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => reject(new Error("First request failed")), 500);
});
const promise2 = new Promise((resolve) => {
setTimeout(() => resolve("Second request succeeded"), 1000);
});
Promise.race([promise1, promise2])
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log(error.message);
});Output:
First request failedThe first promise rejected after approximately 500 milliseconds.
Because Promise.race() follows the first settled promise, the combined promise rejects immediately with that error. It doesn't wait for the second promise to fulfill.
The second operation may continue running even though its result is no longer used by the combined promise.
Real-World Example: Implementing a Timeout
One common use for Promise.race() is creating a timeout for an asynchronous operation.
Imagine you're calling a third-party API and don't want your function to wait indefinitely.
You can race the API request against a timer.
function timeout(ms) {
return new Promise((_, reject) => {
setTimeout(() => {
reject(new Error("Request timed out"));
}, ms);
});
}
async function fetchData() {
try {
const response = await Promise.race([
fetch("https://api.example.com/data"),
timeout(3000)
]);
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error("Unable to fetch data:", error.message);
throw error;
}
}In this example, the function waits for whichever promise settles first.
If the fetch operation takes longer than three seconds, the timeout promise rejects and the function reports a timeout.
However, this pattern doesn't cancel the original HTTP request. The request may continue even after the timeout error has been returned.
For production code, you can use AbortController to cancel a fetch request when a timeout occurs.
Also, the example's timer remains scheduled if the fetch finishes first. A more complete implementation should clear the timer when the request settles.
When Should You Use Promise.race()?
Use Promise.race() when the first settled outcome should determine what happens next.
Common examples include:
Racing an operation against a timeout.
Waiting for the first completed task when either success or failure should end the wait.
Selecting the earliest result from multiple competing asynchronous operations.
Implementing time-based fallbacks.
The important thing to remember is that the winner doesn't have to be successful.
4. What Is Promise.any() in JavaScript?
Promise.any() returns a promise that fulfills as soon as the first input promise fulfills.
Unlike Promise.race(), it ignores individual rejections while waiting for a successful result.
If every input promise rejects, Promise.any() rejects with an AggregateError containing the rejection reasons.
Let's look at a simple example.
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => reject(new Error("Server 1 failed")), 500);
});
const promise2 = new Promise((resolve) => {
setTimeout(() => resolve("Server 2 responded"), 1000);
});
const promise3 = new Promise((resolve) => {
setTimeout(() => resolve("Server 3 responded"), 1500);
});
Promise.any([promise1, promise2, promise3])
.then((result) => {
console.log(result);
})
.catch((error) => {
console.error(error);
});Output:
Server 2 respondedThe first promise rejects after approximately 500 milliseconds.
However, Promise.any() doesn't stop there. It continues waiting for a successful result.
The second promise fulfills after approximately one second, so its value becomes the result.
The third promise might still be running, but its result doesn't change the outcome.
What Happens If Every Promise Rejects?
Consider this example:
const promise1 = Promise.reject(new Error("API 1 failed"));
const promise2 = Promise.reject(new Error("API 2 failed"));
const promise3 = Promise.reject(new Error("API 3 failed"));
Promise.any([promise1, promise2, promise3])
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log(error instanceof AggregateError);
console.log(error.errors.map((err) => err.message));
});Output:
true
[
'API 1 failed',
'API 2 failed',
'API 3 failed'
]Because all three promises rejected, there was no successful result to return.
JavaScript therefore rejects the combined promise with an AggregateError.
The errors property contains the individual rejection reasons in input order.
Real-World Example: Trying Multiple Servers
Suppose your application can retrieve the same public data from several independent servers.
You want to use the first successful response rather than fail because one server is unavailable.
You could use Promise.any():
async function fetchFromAvailableServer() {
const servers = [
"https://server1.example.com/data",
"https://server2.example.com/data",
"https://server3.example.com/data"
];
try {
const response = await Promise.any(
servers.map((url) => fetch(url))
);
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error("Unable to retrieve data:", error);
throw error;
}
}There is an important limitation in this example.
The fetch() promise normally fulfills when an HTTP response arrives, even if the response status is 404 or 500. Therefore, Promise.any() may select a response with an unsuccessful HTTP status before a slower server returns a successful response.
If you want the first successful HTTP response, you should validate the status inside each promise before passing it to Promise.any().
For example:
async function fetchSuccessfulResponse(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
return response;
}
async function fetchFromAvailableServer() {
const servers = [
"https://server1.example.com/data",
"https://server2.example.com/data",
"https://server3.example.com/data"
];
const response = await Promise.any(
servers.map(fetchSuccessfulResponse)
);
return response.json();
}Now, HTTP error responses become rejected promises, so Promise.any() can continue waiting for another server to return a successful response.
This example assumes the servers provide equivalent data and that using the first successful response is appropriate for the application.
When Should You Use Promise.any()?
Use Promise.any() when you need at least one successful result.
Common examples include:
Trying multiple equivalent API endpoints.
Retrieving data from redundant services.
Implementing fallback requests.
Choosing the first successful response from several independent operations.
Remember that Promise.any() does not cancel the other operations after one promise fulfills. If you need cancellation, you'll have to implement it separately.
Promise.all() vs. Promise.allSettled() vs. Promise.race() vs. Promise.any()
Now let's compare all four methods in one place.
Feature |
|
|
|
|
|---|---|---|---|---|
Main purpose | Wait for every promise to fulfill | Collect every promise's outcome | Get the first settled outcome | Get the first fulfilled result |
Fulfills when | All inputs fulfill | All inputs settle | First input fulfills | First input fulfills |
Rejects when | Any input rejects | It doesn't reject because of individual input rejections | First settled input rejects | All inputs reject |
Returns | Array of values | Array of outcome objects | Single value | Single value |
Preserves input order | Yes, in the result array | Yes, in the result array | Not applicable | Not applicable |
Typical use case | Required dashboard data | Independent tasks with individual outcomes | Timeout or first-settled logic | First successful fallback |
The easiest way to remember these methods is to focus on what you need from the group of promises.
Need every operation to succeed? Use
Promise.all().Need to know what happened to every operation? Use
Promise.allSettled().Need the first operation to settle, whether it succeeds or fails? Use
Promise.race().Need the first successful result? Use
Promise.any().
Common Mistakes Developers Should Avoid
Even experienced developers can misuse these methods when working with asynchronous code.
1. Assuming Promise.all() Cancels Other Operations
When one input promise rejects, Promise.all() rejects. But other operations may still be running.
If those operations consume resources or perform side effects, you may need a separate cancellation strategy.
2. Confusing Promise.race() With Promise.any()
This is probably the most important distinction.
Promise.race() returns the result of the first settled promise, even if that promise rejects.
Promise.any() waits for the first fulfilled promise and ignores earlier rejections.
3. Using Promise.allSettled() When You Need Immediate Failure
Promise.allSettled() waits for every input to settle.
If one required operation fails and you need to stop waiting for the overall result, Promise.all() may be more appropriate.
4. Forgetting That HTTP Errors Don't Automatically Reject Fetch
A request returning HTTP 404 or 500 doesn't normally cause the fetch() promise to reject.
If your logic depends on successful HTTP responses, check response.ok and throw an error when appropriate.
5. Starting Too Many Operations at Once
Using Promise.all() with thousands of database queries can overload your application or database.
For large workloads, consider processing tasks in batches or using a concurrency limiter.
6. Assuming These Methods Make CPU-Heavy Code Run in Parallel
Promise combinators coordinate asynchronous results. They don't automatically move CPU-intensive JavaScript calculations to multiple threads.
If your application needs to execute CPU-heavy tasks concurrently across threads, consider worker threads or another suitable processing mechanism.
Final Thoughts
Promise.all(), Promise.allSettled(), Promise.race(), and Promise.any() are all useful tools for managing asynchronous operations in JavaScript and Node.js.
Although they accept similar inputs, they solve different problems.
Use Promise.all() when every operation must succeed. Use Promise.allSettled() when you need the outcome of every operation, even if some fail. Choose Promise.race() when the first settled promise should determine the result, and use Promise.any() when you're looking for the first successful result.
In real projects, choosing the right method can make your code easier to maintain and help you handle failures more effectively.
My suggestion is to experiment with all four methods using promises that resolve or reject after different delays. Once you see how each method behaves, the differences become much easier to remember.
For more details, check the official MDN documentation for Promise and the Node.js documentation.
Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.


