Understanding Promise.all() in JavaScript

Understanding Promise.all() in JavaScript

If you are a JavaScript developer, you must have come across promises in your code. Promises are a way of handling asynchronous operations in JavaScript. Promise.all() is a method that takes an array of promises and returns a new promise that resolves when all the promises in the array have resolved. In this article, we will explore Promise.all() in detail, including its usage, related concepts, and methods.

What is Promise.all()?

Promise.all() is a method that takes an array of promises and returns a new promise that resolves when all the promises in the array have resolved. If any of the promises in the array reject, then the Promise.all() method rejects with the reason of the first promise that rejects. If all the promises are resolved, then the Promise.all() method resolves with an array of the resolved values in the order of the input promises.

Usage of Promise.all()

Let’s take an example to understand how Promise.all() works. Suppose we have to fetch data from two different APIs and wait for both responses to complete before rendering the data on the front-end. We can use Promise.all() to achieve this.

const promise1 = fetch('https://api1.com');
const promise2 = fetch('https://api2.com');

Promise.all([promise1, promise2])
  .then(([response1, response2]) => {
    // Handle response1 and response2
  })
  .catch((error) => {
    // Handle error
  });

In the above code, we are calling the fetch() method to fetch data from two different APIs. We are storing the returned promises from these methods in variables promise1 and promise2. We are then passing these promises as an array to Promise.all() method. The .then() method on Promise.all() method returns an array of resolved values from promise1 and promise2. We are using destructuring to get these resolved values. If any of the promises reject, the .catch() method will be called with the reason of the first promise that rejects.

Promise.race()

Promise.race() is a method that takes an array of promises and returns a new promise that resolves or rejects as soon as one of the promises in the array resolves or rejects. If the first promise to settle is a resolved promise, then the Promise.race() method resolves with the value of the first promise to resolve. If the first promise to settle is a rejected promise, then the Promise.race() method rejects with the reason of the first promise to reject.

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

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

Promise.race([promise1, promise2])
  .then((value) => {
    console.log(value);
  })
  .catch((error) => {
    console.log(error);
  });

In the above code, we are creating two promises promise1 and promise2. promise1 resolves after 1 second, and promise2 rejects after 500 milliseconds. We are passing these promises as an array to Promise.race() method. Since promise2 rejects first, the .catch() method is called with the reason of promise2.

Async/Await

Async/await is a way of writing asynchronous code that looks synchronous. Async/await is built on top of Promises. Async functions always return a promise, which can be resolved or rejected. We can use the await keyword to wait for a promise to resolve before moving on to the next line of code.

async function fetchData() {
  const response = await fetch('https://api.com');
  const data = await response.json();
  return data;
}

fetchData()
  .then((data) => {
    console.log(data);
  })
  .catch((error) => {
    console.log(error);
  });

In the above code, we are using the async keyword to define an asynchronous function fetchData(). We are using the await keyword to wait for the response from the API before moving on to the next line of code. The fetchData() function returns a promise that can be resolved or rejected. We are using .then() and .catch() methods to handle the resolved data or rejected error.

Conclusion

In this article, we explored Promise.all() in detail, including its usage, related concepts, and methods. Promise.all() is a powerful method that can be used to handle multiple asynchronous operations in JavaScript. Understanding Promise.all() and related concepts will help you write better asynchronous code in JavaScript.