What is promise.all() and how to use it?

How to use promise.all()

Promise is an special javascript object which use to do something in future. Like in real life when you commit to someone that’s the commitment for the upcoming time. Same as promises has two possibilities as resolved and rejected.

Today we will learn about it’s one of method named as Promise.all().

What is promise.all()?

The Promise.all() method is actually a promise that takes an array of promises(an iterate) as an input. It returns a single Promise that resolves when all of the promises passed as an iterate. Which have resolved or when the iterate contains no promises. In simple way, if any of the passed-in promises reject, the Promise.all() method asynchronously rejects the value of the promise that already rejected, whether or not the other promises have resolved.

Let’s quick view in code:

Promise.all([p1, p2, p3])
 .then(result) => {
   console.log(result)
 })
 .catch(error => console.log(`Error in promises ${error}`))

As you can see, we parsed an array to Promise.all() method, Once all promises will be resolved then output will consoled.

Let’s look on example :

var Promise1 = Promise.resolve(10);
var Promise2 = 779;
var Promise3 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("cooding");
  }, 100);
});

Promise.all([p1, p2, p3]).then(response => {
  console.log(response); 
});
//output
[10, 779, "cooding"]

In the event that the iterable contains non-promises values, they are ignored. Yet included in the returned promise array values.

How promises reject if any promises gone failed?

Let’s call an function as doOperation

var doOperation = function(time) {
  return new Promise(function (resolve, reject) {
    setTimeout(function() {
      if(time === 2000) {
        reject("error at 2000");
      }
      resolve(time);
    }, time);
  });
}

It will be reject if time is equal to 2000 , Promise.all should reject instantly

var promisesCall = [doOperation(2000), doOperation(1000), doOperation(3000)];

var promises = promiseAll(promisesCall);

promises.then(function(results) {  
     console.log(results); 
}).catch(function(error) {
     console.log(error);});

It will return an erros at 2000 , Because promise value meet the condition which is equal to 2000.

Recommended

Learn JavaScript resources in 2021

Author: Shantun Parmar

Comments are closed.