Promise.all() receives an array as a parameter. When all promises of the array are in the state of resolve, Promise.all() will succeed. If there is a failure, it will be considered as a failure. For example:
var p1 = Promise.resolve('a');
var p2 = Promise.resolve('b');
var p3 = Promise.resolve('c');
Promise.all([p1,p2,p3]).then(function(value) {
console.log(value);
})
No doubt, the result of the above code is a,b,c. Because P1, P2 and P3 are all successful states. Let's go on to the next example:
var p1 = new Promise((resolve, reject) => {
resolve('hello');
})
.then(result => result)
.catch(e => e);
var p2 = new Promise((resolve, reject) => {
throw new Error('Wrong report');
})
.then(result => result)
.catch(e => e);
Promise.all([p1,p2])
.then(function(value) {
console.log(value);
})
.catch(function(re) {
console.log(re);
})
Is this all going to fail? Well, I thought so at first, but after a careful analysis of this code, we will find that it is not as simple as we think. Let's analyze:
- p1 is undoubtedly successful;
- p2 throws an error directly in the function. But notice that p2 has its own catch function, which can catch the errors thrown in front;
- Because p2 can catch errors by itself, in the Promise.all () method, both promises p1 and p2 are in the state of resolve, so the callback function specified by the then method will be called.
Next, let's take a look at the process of implementing the Promise.all() method. In that sentence, we need to make sure that the parameter received by this method is an array and the return is a promise object.
function promiseAll(promises){
return new Promise(function(resolve,reject) {
//promises must be an array
if(!(promises instanceof Array)) {
throw new TypeError("promises must be an Array");
}
var len = promises.length,
resolvedCount = 0,
resolvedArray = new Array(len);
for(var i = 0;i < len ;i++) {
(function(i) {
Promise.resolve(promises[i])
.then(value => {
resolvedCount++;
resolvedArray[i] = value;
if(resolvedCount == len) {
return resolve(resolvedArray);
}
},re => {
return reject(re);
})
.catch(re => {
console.log(re);
})
})(i)
}
})
}