Back to all questions

What is the difference between Promise.all and Promise.allSettled?

Devs Hive

Devs Hive

Seen on interview: 4 users

Both methods work with an array of promises: they run them in parallel and wait for them to finish. However, they behave differently, so it is important, both in interviews and in real-world work, to understand the difference between them and to know which method is more appropriate in which situations.

Promise.all

This method takes an array of promises and returns an array of results in the same order in which we passed the promises. If all of them complete successfully, Promise.all resolves successfully (fulfilled), but if at least one is rejected (rejected), Promise.all immediately rejects with an error and does not wait for the promises that are still in progress (pending).

async function loadProducts() {
const ids = [1, 2, 3];

const products = await Promise.all(
ids.map(async (id) => {
const res = await fetch(`https://api.example.com/products/${id}`);
return res.json();
})
);

console.log(products); // масив з 3 продуктів
/*
[
{
"id": 1,
"name": "iPhone 15",
"price": 999
},
{
"id": 2,
"name": "MacBook Air",
"price": 1299
},
{
"id": 3,
"name": "AirPods Pro",
"price": 249
}
]
*/
}

loadProducts();

Promise.allSettled

It also runs an array of promises in parallel, but it waits until all of them have settled fulfilled/rejected, and then returns an array of objects with the data or the reason for the error. As you can see from the API response, Promise.allSettled completed successfully even though it contained a rejected promise. This is the difference between Promise.all and Promise.allSettled.

const upload = (file) =>
fetch("/photos", { method: "POST", body: file }).then((r) => {
if (!r.ok) throw new Error("Upload failed");
return r.json();
});

Promise.allSettled([
upload(file1),
upload(file2),
Promise.reject(new Error("Network error"))
]).then((results) => console.log(results));

/*
Приклад відповіді (від Promise.allSettled):

[
{
"status": "fulfilled",
"value": { "id": "ph_101", "url": "https://cdn.example.com/ph_101.jpg" }
},
{
"status": "fulfilled",
"value": { "id": "ph_102", "url": "https://cdn.example.com/ph_102.jpg" }
},
{
"status": "rejected",
"reason": "Error: Network error"
}
]
*/

When to use which

Promise.all is best used for idempotent operations. In the case of a rejection, we can easily do Retry and restart all the promises. Most often this means fetching or updating data. If you don't know what idempotency is, I recommend reading about it here, since it is also a common Node.js interview question.

Promise.allSettled is best used when creating entities. Since the state of the system changes, we can't simply retry all the promises. With allSettled, we can pick the promises that ended up rejected and restart them separately.

A simple example of using allSettled is завантаження багатьох картинок в галерею. For example, you upload 10 photos at once, and 7 of them upload successfully while three fail. Then we can show the user that there are problems with three images, and they can either delete them or try uploading them again.

Seen on interview?

Comments (0)

Sign in to leave a comment

No comments yet. Be the first!