How do you use Promise.all() in JavaScript?

Promise.all() is a method in JavaScript that allows us to execute multiple asynchronous operations at once and wait for all of them to complete before moving on to the next step in our code.

It is especially useful when we need to make several API calls and wait for all of them to return their data before processing it further.

Here’s a brief overview of how to use Promise.all() in JavaScript:

  1. Create an array of promises.
  2. Pass that array into Promise.all().
  3. Use .then() to handle the resolved values.

Let’s dive into each of these steps:

1. Create an array of promises

To use Promise.all(), we need to first create an array of promises. A promise is an object that represents a value that may not be available yet, but will be in the future. We can create a promise using the Promise() constructor.

For example:

const promise1 = new Promise((resolve, reject) => {
  // Do some asynchronous operation
  // If the operation is successful, call resolve() with the result
  // If the operation fails, call reject() with an error message
});

const promise2 = new Promise((resolve, reject) => {
  // Do some other asynchronous operation
});

const promisesArray = [promise1, promise2];

In this example, we’ve created two promises using the Promise() constructor and pushed them into an array called promisesArray.

2. Pass the array of promises into Promise.all()

Once we have an array of promises, we can pass it into Promise.all(). This method takes an array of promises as its argument and returns a new promise that resolves with an array of resolved values from the promises passed in.

For example:

Promise.all(promisesArray)
  .then((valuesArray) => {
    // Do something with the resolved values
  })
  .catch((error) => {
    // Handle errors that occurred in any of the promises
  });

In this example, we’re passing the promisesArray into Promise.all(). We then use the .then() method to handle the resolved values. The valuesArray parameter of the .then() function contains an array of resolved values from each promise in the promisesArray. We can use this array to do something with the resolved data. If any of the promises in the array fail, the .catch() method will be called with an error object.

3. Use .then() to handle the resolved values

Now that we know how to create an array of promises and pass it into Promise.all(), let’s look at an example of how to use .then() to handle the resolved values.

In this example, we’ll make two API calls to get information about two different GitHub users, and then we’ll log their information to the console.

For example:

const user1 = "octocat";
const user2 = "mojombo";

const promise1 = fetch(`https://api.github.com/users/${user1}`).then(
  (response) => response.json()
);
const promise2 = fetch(`https://api.github.com/users/${user2}`).then(
  (response) => response.json()
);

Promise.all([promise1, promise2])
  .then((values) => {
    console.log(`User 1: ${values[0].name}`);
    console.log(`User 2: ${values[1].name}`);
  })
  .catch((error) => {
    console.error(error);
  });

In this example, we’re using the fetch() function to make two API calls to get information about two different GitHub users. We’re using template literals to insert the user1 and user2 variables into the URLs. We’re then using the .then() method to extract the JSON data from the response using the response.json() method.

We’re creating two promises, promise1 and promise2, that will resolve with the JSON data from the API calls. We’re then passing those promises into Promise.all(). In the .then() method, we’re using the values array to log the names of the two GitHub users to the console.

If any of the promises fail, the .catch() method will be called with an error object. We’re using console.error() to log the error to the console.

Note that the order of the resolved values in the values array will correspond to the order of the promises in the array passed to Promise.all(). So in our example, the first value in the values array will be the data for user1, and the second value will be the data for user2.

Thank you for reading, and let’s have conversation with each other

Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.

Read more: