How to Wait for All Promises to Settle in JavaScript?

Introduced in ES11, you can use the Promise.allSettled() method, which waits for all promises to settle — i.e. it waits till all the given promises are either fulfilled or rejected. Upon completion, it returns a single Promise that resolves to an array of objects which describes the outcome of each promise:

// ES11+
const p1 = Promise.resolve(1);
const p2 = Promise.reject('foo');
const p3 = 3;

Promise.allSettled([p1, p2, p3])
    .then((values) => console.log(values));

/* [
    { status: 'fulfilled', value: 1 },
    { status: 'rejected', reason: 'foo' },
    { status: 'fulfilled', value: 3 },
] */

As you can see in the example above, depending on whether the promises resolved or rejected, the resulting array of objects each contains a status string:

  • If the status is "fulfilled", then a value property is present;
  • If the status is "rejected", then a reason property is present.

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.