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

Marius Schulz
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
Yash Gupta
~ a year 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');
});