What is the difference between promise.all and promise.allsettled?
## Understanding Promise.all and Promise.allSettled
### Introduction
In JavaScript, handling asynchronous operations is crucial for building efficient applications. Two commonly used methods for managing multiple promises are `Promise.all` and `Promise.allSettled`. This document outlines the differences between these two methods, their use cases, and provides code examples for better understanding.
### Promise.all
The `Promise.all` method takes an array of promises and returns an array with the results in the same order as the promises were passed. If all of them are fulfilled successfully, then `Promise.all` resolves successfully (fulfilled). However, if at least one promise is rejected (rejected), `Promise.all` immediately rejects with an error and does not wait for any promises that are still pending (pending).
```javascript
async function fetchBooks() {
const bookISBNs = ['978-3-16-148410-0', '978-1-60309-452-8', '978-0-06-112008-4'];
const bookDetails = await Promise.all(
bookISBNs.map(async (isbn) => {
const response = await fetch(`https://api.library.com/books/${isbn}`);
return response.json();
})
);
console.log(bookDetails); // array of 3 books
/*
[
{
"isbn": "978-3-16-148410-0",
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald"
},
{
"isbn": "978-1-60309-452-8",
"title": "Maus",
"author": "Art Spiegelman"
},
{
"isbn": "978-0-06-112008-4",
"title": "To Kill a Mockingbird",
"author": "Harper Lee"
}
]
*/
}
fetchBooks();Promise.allSettled
The Promise.allSettled method also runs an array of promises in parallel but waits until all are settled (fulfilled/rejected). After all promises have settled, it returns an array of objects with data or the reason for the error. Notably, Promise.allSettled resolves successfully even if one or more promises are rejected, which is the key difference from Promise.all.
const sendReview = (review) =>
fetch("/reviews", { method: "POST", body: JSON.stringify(review), headers: { "Content-Type": "application/json" } })
.then((response) => {
if (!response.ok) throw new Error("Review submission failed");
return response.json();
});
Promise.allSettled([
sendReview({ reviewer: "Alex", content: "Loved the product!" }),
sendReview({ reviewer: "Jordan", content: "Not what I expected." }),
Promise.reject(new Error("Server error"))
]).then((outcomes) => console.log(outcomes));When and What to Use
Use Cases for Promise.all
Promise.all is best used for idempotent operations. In the case of a rejected promise, we can easily perform a retry and restart all promises. This is often the case for fetching or updating data. If you are not familiar with idempotency, I recommend reading here, as this is also a common question in Node.js interviews.
Use Cases for Promise.allSettled
Promise.allSettled is best used when creating entities. Since the state of the system changes, we cannot simply retry all promises. With Promise.allSettled, we can select the promises that were rejected and restart them separately.
A simple example of using Promise.allSettled is uploading multiple images to a gallery. For instance, if you are uploading 10 photos simultaneously, and 7 of them upload successfully while three encounter errors, we can inform the user that there are issues with three images, and they can either remove them or try to upload them again.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.