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:
Expand|Select|Wrap|Line Numbers
- ```
- Promise.all([p1, p2, p3])
- .then(result) => {
- console.log(result)
- })
- .catch(error => console.log(`Error in promises ${error}`))
- ```
Let's look on example :
Expand|Select|Wrap|Line Numbers
- 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"]
How promises reject if any promises gone failed?
Let's call an function as doOperation
Expand|Select|Wrap|Line Numbers
- var doOperation = function(time) {
- return new Promise(function (resolve, reject) {
- setTimeout(function() {
- if(time === 2000) {
- reject("error at 2000");
- }
- resolve(time);
- }, time);
- });
- }
Expand|Select|Wrap|Line Numbers
- 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);});