Wait for all promises to resolve in JavaScript

As we know that JavaScript is a non-blocking language so it does not wait for any async code to get resolved instead it sends it to a event loop and moves to the next code block.

But there are many situations when we need to wait for multiple promises or async actions to get resolved at once in JavaScript. If we only have one or two sequential calls then we solve it easily. But what if we have many calls that don’t need to resolve sequentially?

In this post, we will learn how to wait for all promises to resolve parallelly using the Promise.all() and Promise.allSettled() method.

How to wait for all promises to resolve in JavaScript?

JavaScript has multiple built-in methods to we can use to wait for all promises to get resolved.

  1. The Promise.all() method
  2. The Promise.allSettled() method

1. The Promise.all() method

To wait for all promises to resolve in JavaScript, use Promise.all() method.

The Promise.all() method accepts an array of promises as a parameter and returns a single Promise that resolves to an array of the results of the input promises.

The returned promise fulfils with an array of fulfilment values when every item in the array fulfils and rejects with the first rejection reason if any item rejects.

JavaScript
const p1 = Promise.resolve('Hello World!');
const p2 = Promise.resolve('200');
const p3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'Resolved');
});

Promise.all([p1, p2, p3]).then((values) => {
  // 👇️ this runs
  console.log(values);
}).catch(err => {
  console.log(err);
})

// output  👉️ [ 'Hello World!', '200', 'Resolved' ]

We used Promise.all() and passed an array of promises as input. Once this is resolved, it will run the then() block.

⚠️ Note that if any promise is rejected, it will terminate the current process and go to catch() block with that rejection error.

JavaScript
const p1 = Promise.resolve('200');
const p2 = Promise.reject('Rejected');
const p3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'resolved');
});

Promise.all([p1, p2, p3]).then((values) => {
  console.log(values);
}).catch(err => {
  // 👇️ this runs
  console.log(err);
})

// output  👉️  Rejected

Since our second promise was rejected, the catch block ran.

As we saw in the above example, the Promise.all() terminates the process if any promise gets rejected.

As we discussed, Promise.all() immediately terminates the process if any promise gets rejected.

However sometimes, we have to wait until all promises are completed, even if some are rejected.

To wait until all promises are complete even if some rejected, use the  Promise.allSettled() method.


2. The Promise.allSettled() method

The Promise.allSettled() accepts an array of promises as input and returns an array of the objects where each object has a description of the outcome of each Promise.

JavaScript
const p1 = Promise.resolve('200');
const p2 = Promise.reject('Rejected');
const p3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'resolved');
});

Promise.allSettled([p1, p2, p3]).then(res => { 
  // 👇️ this runs
  console.log(res);
}).catch(err => {
  console.log(err);
});

// 👇️ output
// [
//   { status: 'fulfilled', value: '200' },
//   { status: 'rejected', reason: 'Rejected' },
//   { status: 'fulfilled', value: 'resolved' }
// ]

In the above example, our second promise was rejected, but still, it proceed all the promises and returned an array of objects.

For each result object, a status string is present. If the status is fulfilled, then a value is present. If the status is rejected, then a reason is present.

The value (or reason) reflects what value each promise was fulfilled (or rejected) with.

There are three statuses then can assign to the promises in JavaScript: pending, fulfilled, and rejected.

StatusDescription
pendingWhen a promise is initially created
fulfilledIf the operation is successful
rejectedIf the operation is unsuccessful

How to call the Promise.all() and Promise.allSettled() method using async – await?

You can use async await with Promise.all()and Promise.allSettled()like you use it with other methods and functions.

JavaScript
const p1 = Promise.resolve('Hello World!');
const p2 = Promise.resolve('200');
const p3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'Resolved');
});

const resolvedPromises = await Promise.all([p1, p2, p3]);
console.log(resolvedPromises); // 👉️ [ 'Hello World!', '200', 'resolved' ]

const settledPromises= await Promise.allSettled([p1, p2, p3]);
console.log(settledPromises);
// 👇️ output
// [
//   { status: 'fulfilled', value: 'Hello World!' },
//   { status: 'fulfilled', value: '200' },
//   { status: 'fulfilled', value: 'resolved' }
// ]

Conclusion

In conclusion, you can wait for all promises to resolve using the Promise.allSettled() and Promise.all() methods. You can use any method you as per requirement.


Learn More:

Unlock your programming potential with Stack Thrive! Discover step-by-step tutorials, insightful tips, and expert advice that will sharpen your coding skills and broaden your knowledge.

Leave a Comment

Facebook Twitter WhatsApp