JavaScript Promise all() Method Tutorial

In this section, we will learn what the Promise all() method is and how to use it in JavaScript.

What is Promise all () Method in JavaScript?

Sometimes we want to send a request to multiple external resources like servers and only when we got responds from all the servers, a set of instructions should be run. This is where the `Promise.all()` method comes in handy.

Promise all () Method Syntax:

Promise.all(iterableObject);

Promise all () Method Parameters

The `all()` method takes an iterable object (like an array) that has a bunch of promise-objects as its elements.

Promise all () Method return value

This method creates a promise that will be resolved only when all the promises in the iterable object are resolved.

This means if at least one contained promise remains pending, the composed promise also will remain pending. Also, if one contained promise rejects, the composed promise will reject as well.

Note: if we pass an empty iterable object (like an empty array) the composed promise will be settled to `Promise.resolve()`.

Example: using Promise all () method in JavaScript

const prom1 = new Promise((resolve,reject)=>{
  setTimeout(()=>{
    resolve("The first promise resolved");
  },2000);
});
const prom2 = new Promise((resolve, reject)=>{
  setTimeout(()=>{
    reject("The second promise rejected");
  },1000);
});
const prom3 = Promise.reject("Sorry to fail!");
const prom = Promise.all([
  prom1, prom2,prom3
  ]);
prom.then(resolve=>{
  console.log(resolve);
}).catch(reject=>{
  console.log(reject);
})

Output:

Sorry to fail!

In the array that we passed to the `all()` method, there two promise-objects that will settle to reject. These promises are `prom2` and `prom3`. In situations like this, the composed promise will also settle to rejection with the reason that it gets from the first rejected Promise.

So here, because the `prom3` rejected first, the composed Promise used the reason of the `prom3` to run the rejection handler.

Example: JavaScript Promise all() Method

const prom1 = new Promise((resolve,reject)=>{
  setTimeout(()=>{
    resolve("The first promise resolved");
  },2000);
});
const prom2 = new Promise((resolve, reject)=>{
  setTimeout(()=>{
    resolve("The second promise resolved");
  },5000);
});
const prom3 = Promise.resolve("Settled to resolve");
const prom = Promise.all([
  prom1, prom2,prom3
  ]);
prom.then(resolve=>{
  console.log(resolve);
}).catch(reject=>{
  console.log(reject);
})

Output:

["The first promise resolved", "The second promise resolved", "Settled to resolve"]

Note:

  • When all the promises in the iterable object of the `all()` method resolved, the value that will be passed to the resolve-handler of the composed Promise, is an array that contains the values that were passed to each `resolve` method for each Promise object.
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies