Wait for Multiple JavaScript Promises to Settle with Promise.allSettled()

InstructorMarius Schulz

Share this video with your friends

Send Tweet

The Promise.allSettled() method accepts an array (or any other iterable) of promises as a parameter. It returns a Promise object that is fulfilled with an array of settlement objects. Each settlement object describes the settlement of the corresponding input promise.

Notice that the Promise object returned from the Promise.allSettled() method is only rejected if there's an error iterating over the input promises. In all other cases, it is fulfilled.

The Promise.allSettled() method is useful when you want to wait for multiple promises to settle, no matter whether they'll be fulfilled or rejected.

Yash Gupta
~ 5 years ago

Why does the Promise.allSettled() methods execute faster in this scenario even though I have disabled network caching?

The order seems to matter what will execute faster. If there is some caching going on where can I learn more about the internal caching mechanism? (Which is not happening due to network request being cached as I have already disabled it in my browser.)

const query = endpoint =>
  fetch(`https://jsonplaceholder.typicode.com/${endpoint}`).then(res =>
    res.json()
  );

Promise.all([query(`users`), query(`posts`)]).then(([users, posts]) => {
  console.time('Promise.all');
  console.log(`Promise.all`);
  console.log(users);
  console.log(posts);
  console.timeEnd('Promise.all');
});

Promise.allSettled([query(`users`), query(`posts`)]).then(([users, posts]) => {
  console.time('Promise.allSettled');
  console.log(`Promise.allSettled`);
  console.log(users.value);
  console.log(posts.value);
  console.timeEnd('Promise.allSettled');
});
Kunal Ranjan
~ 3 years ago

Hello schulz, why do .catch handler is unable to handle rejection in case all of the request is being failed.

Marius Schulzinstructor
~ 3 years ago

@Kunal: The promise returned by the Promise.allSettled() method is never rejected. As a result, you can't use the .catch() method to handle the case in which all promises were rejected. Instead, you should inspect the status property of the various fulfilment objects and check whether it's set to "rejected" for all promises.