What is the promise.all() Method in JavaScript?

JavaScript is an asynchronous language that, most of the time, relies on promises to handle asynchronous operations. Developers face situations where multiple asynchronous tasks need to be executed concurrently, and we need a way to wait until all of them are completed before proceeding. This is where the Promise.all in JavaScript comes into play. In this blog, let us explore what js Promise.all is, its syntax and usage examples, and address common questions such as its differences from Promise. Race, handling non-promise values, managing promise rejections, compatibility, and interplay with async/await.

Promise.all in javaScript can work in the following way-

  1. All or Nothing: Promise.all() waits for all promises in the iterable to settle, meaning they either all resolve or at least one rejects.
  2. Single Promise Result: It returns a single promise that fulfills with an array of results when all promises in the iterable are fulfilled. The order of the results corresponds to the order of the promises in the iterable.
  3. First Rejection: If any promise in the iterable is rejected, the whole Promise.all() is rejected with the reason of the first rejected promise. Subsequent rejections are ignored.

Syntax

The syntax of js Promise.all is relatively straightforward:

Promise.all(iterable); 

Here, iterable is an array or any iterable object containing promises. The Promise.all method returns a single promise that resolves when all the promises in the iterable have been resolved or rejected with the reason of the first promise that was rejected.

JavaScript Promise.all() Method Examples

Let us look at some practical examples to understand how Promise.all in JavaScript works in different scenarios.

Example 1: Basic usage

Syntax:

const promise1 = new Promise(resolve => setTimeout(() => resolve('One'), 1000));
const promise2 = new Promise(resolve => setTimeout(() => resolve('Two'), 2000));
const promise3 = new Promise(resolve => setTimeout(() => resolve('Three'), 3000));
Promise.all([promise1, promise2, promise3])
  .then(values => console.log(values))
  .catch(error => console.error(error));

In this example, we create three promises that resolve after different time intervals. The js Promise.all method is used to wait for all promises to resolve, and then the values are logged. If any promise.all in javascript is rejected, the catch block captures the first rejection.

Example 2: Handling Non-Promise values

const promise1 = Promise.resolve(1);
const promise2 = 'Not a promise';
const promise3 = new Promise(resolve => setTimeout(() => resolve('Three'), 1000));
Promise.all([promise1, promise2, promise3])
  .then(values => console.log(values))
  .catch(error => console.error(error));

Here, promise2 is not a promise, but Promise.all() still works. The non-promise values are treated as resolved promises, allowing the method to handle a mix of promises and non-promise values.

Conclusion

Promise.all in JavaScript is a useful tool that is used for handling multiple asynchronous operations in JavaScript. This tool simplifies the code and makes it more readable and easy for the coders. The js Promise.all method proves to be a valuable asset in situations where multiple asynchronous operations need to be handled constantly. Promise.all syntax and ability to streamline code make it a preferred choice for developers who want to enhance the efficiency of their applications. 

If you are looking to enhance your software development skills further, we would highly recommend you to check Simplilearn’s Full Stack Java Developer. This course can help you hone the right skills and make you job-ready.

If you have any questions or queries, feel free to post them in the comments section below. Our team will get back to you at the earliest.

FAQs

1. What is the difference between Promise.all and Promise.race?

While Promise.all in JavaScript waits for all promises in the iterable to be resolved or rejected Promise.race returns as soon as one of the promises in the iterable is settled. It's a race to see which promise settles first. This can be useful in scenarios where you only need the result of the first settled promise.

Consider the following example:

Syntax:

const promise1 = new Promise((resolve) => setTimeout(resolve, 100, 'First'));
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 200, 'Second'));

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

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

In this example, Promise.all() catches the rejection of promise2 and logs the error while Promise.race() resolves with the value of the first fulfilled promise, which is promise1.

2. Can I use Promise.all with non-promise values?

Yes, Promise.all in JavaScript is flexible enough to handle a mix of promises and non-promise values in the iterable. Non-promise values are treated as already fulfilled promises. The resulting promise from Promise.all() will be fulfilled with an array of all the values, whether they are promises or not.

const promise1 = new Promise((resolve) => setTimeout(resolve, 100, 'First'));
Promise.all([promise1, 'Non-promise value', 42])
  .then((values) => {
    console.log(values);
    // Output: ['First', 'Non-promise value', 42]
  })
  .catch((error) => {
    console.error(error);
  });

3. How can I handle promise rejections with Promise.all()?

Handling promise rejections with Promise.all() involves using the .catch() method on the returned promise. This method is invoked if any of the input promises are rejected.

const promise1 = new Promise((resolve, reject) => setTimeout(reject, 100, 'Error'));
Promise.all([promise1])
  .then((values) => {
    console.log(values);
  })
  .catch((error) => {
    console.error(error);
    // Output: Error
  });

In this example, the .catch() block captures the rejection reason of promise1.

4. Is Promise.all Supported in All JavaScript Environments?

Promise.all in JavaScript is a standard ECMAScript 6 (ES6) feature and is widely supported in modern JavaScript environments. Also, verifying the compatibility with the specific environments your application targets is essential. Generally, all major browsers and Node.js support Promise.all().

However, anyone working in an environment that does not support ES6 features may face compatibility issues. In such cases, consider using a transpiler like Babel to convert your code to a compatible version.

5. Can I use async/await with Promise.all()?

Yes, Combining async/await with Promise.all in JavaScript enhances the readability of asynchronous code. The async/await syntax allows you to work with promises more synchronously.

async function fetch data() {
  const promise1 = fetch('https://api.example.com/data1');
  const promise2 = fetch('https://api.example.com/data2');
  const promise3 = fetch('https://api.example.com/data3');
  try {
    const responses = await Promise.all([promise1, promise2, promise3]);
    const data = await Promise.all(responses.map((response) => response.json()));
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}
fetchData();

In this example, the fetchData function asynchronously fetches data from multiple endpoints using fetch and js Promise.all(). The await keyword simplifies the handling of promises, making the code cleaner and more readable.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 24 Feb, 2025

6 Months$ 8,000
Automation Test Engineer Masters Program

Cohort Starts: 8 Jan, 2025

8 months$ 1,499
Full Stack Java Developer Masters Program

Cohort Starts: 8 Jan, 2025

7 months$ 1,449
Full Stack (MERN Stack) Developer Masters Program

Cohort Starts: 8 Jan, 2025

6 Months$ 1,449