Promise.all()接收一个数组为参数,当数组的所有Promise都为resolve的状态时,Promise.all()才会成功;若有一个失败,都会被认为是失败的。举个小例子:
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);
})
不用怀疑,上面这段代码的运行结果就是a,b,c。因为p1,p2,p3都是成功的状态。那么再继续看下一个例子:
var p1 = new Promise((resolve, reject) => {
resolve('hello');
})
.then(result => result)
.catch(e => e);
var p2 = new Promise((resolve, reject) => {
throw new Error('报错了');
})
.then(result => result)
.catch(e => e);
Promise.all([p1,p2])
.then(function(value) {
console.log(value);
})
.catch(function(re) {
console.log(re);
})
此时大家的第一个想法是不是这个all会失败呢?嗯,其实我开始也是这样认为的,但是认真分析一下这段代码就会发现其实并不是我们想的那么简单的。下面我们来分析一下:
- p1肯定毫无疑问是成功的;
- p2在函数里直接抛出一个错误。但是注意了,p2有自己的catch的函数,catch函数是可以捕获到前面抛出的错误的;
- 因为p2自己可以捕获到错误,所以在Promise.all()方法里p1,p2两个Promise都是resolve的状态,因此会调用then方法指定的回调函数。
接下来我们再看一下实现Promise.all()方法的过程。还是那句话我们要明确这个方法接收的参数是数组并且返回的是promise对象。
function promiseAll(promises){
return new Promise(function(resolve,reject) {
//promises必须是一个数组
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)
}
})
}