Home » How to Use Promise.all()
How to Use Promise.all()

How to Use Promise.all()

Introduction:

JavaScript uses Promise.all() to manage asynchronous operations efficiently, providing a streamlined approach for handling concurrent tasks in programming. They represent an operation that hasn’t been completed yet and simplify deferred computations. A promise can fulfill, reject, settle, or remain pending, illustrating its dynamic states and outcomes in various scenarios. Promises are crucial for managing asynchronous tasks efficiently in JavaScript.

Promise.all() and Its Significance:

Promise.all() is a method in JavaScript that takes an iterable of promises and returns a single promise. It waits for all promises to settle, meaning they either all resolve or at least one rejects. When all promises fulfill, the iterable yields an array of results, ordered based on the promises’ sequence. If any promise is rejected, Promise.all() is rejected with the reason of the first rejected promise. This method is valuable for handling multiple asynchronous operations concurrently and simplifying code by waiting for all promises to complete before proceeding.

Promise all Example

1. Promise.all():

Here is an example of using the Promise.all() method to fetch data from multiple APIs:

const fetchAPI1 = fetch('https://api.example.com/data1');
const fetchAPI2 = fetch('https://api.example.com/data2');
const fetchAPI3 = fetch('https://api.example.com/data3');

Promise.all([fetchAPI1, fetchAPI2, fetchAPI3])
  .then(responses => Promise.all(responses.map(response => response.json())))
  .then(data => {
    console.log(data[0]); // data from API1
    console.log(data[1]); // data from API2
    console.log(data[2]); // data from API3
  })
  .catch(error => console.error(error));

This example employs the Promise.all() method to retrieve data from three distinct APIs. The fetch() method returns a promise that resolves to the response object. The Promise.all() method waits for all three promises to resolve and returns an array of response objects. The map() method extracts JSON data from every response object, sending the data from each API to the console.


Using Promise.all(), efficiently manage multiple asynchronous operations and process their results upon completion.

2. Example: all promises fulfilled

Here is an example of using the Promise.all() method when all promises are fulfilled:

const promise1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Promise 1 resolved');
  }, 1000);
});

const promise2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Promise 2 resolved');
  }, 2000);
});

const promise3 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Promise 3 resolved');
  }, 3000);
});

Promise.all([promise1, promise2, promise3])
  .then(values => {
    console.log(values);
  })
  .catch(error => {
    console.error(error);
  });

Output:

Promise.all example 1


In this example, we create three promises with distinct timeout values using the Promise constructor. We employ the Promise.all() method to await the resolution of all three promises, obtaining an array of their resolved values. The then() method logs these values to the console. As all promises fulfill their resolution, the catch() method remains unexecuted.


Utilize Promise.all() to efficiently manage multiple asynchronous operations and process their results upon completion.

3. Example: one promise rejects

Here is an example of using the Promise.all() method when one promise rejects:

const promise1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Promise 1 resolved');
  }, 1000);
});

const promise2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject('Promise 2 rejected');
  }, 2000);
});

const promise3 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Promise 3 resolved');
  }, 3000);
});

Promise.all([promise1, promise2, promise3])
  .then(values => {
    console.log(values);
  })
  .catch(error => {
    console.error(error);
  });

Output:

Promise example 2

This example involves creating three promises using the Promise constructor, each having a distinct timeout value. Rejecting intentionally with the reject() method occurs in the second promise. Utilize Promise.all() to await resolution or rejection of all three promises, obtaining an array of their outcomes. The catch() method is executed, logging the error message to the console when one promise is rejected.

Efficiently handle multiple asynchronous operations with Promise.all(), ensuring result processing after completion, even if one rejects.

Conclusion:

Promise.all() is a valuable, concise tool for JavaScript developers, efficiently handling diverse asynchronous operations. Boost app performance, streamline error handling, ensure optimal transactions with Promise.all() for efficient execution. Simplify the user experience by including Promise.all() in your asynchronous workflow for cleaner, maintainable code.

More Reading

Post navigation

Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *