关于Promise.all()是如何确保所有的promise都被执行完之后再去调用resolve(result)的
今天看网上关于promise的实现源码,看到Promise.all()的实现的时候有些不理解了,这段代码是如何确保所有的promise都被执行完之后再去调用resolve(result)的,代码如下,请大神指点。
Promise.all = function(promises){
if (!isArray(promises)) {
throw new TypeError('You must pass an array to all.');
}
return Promise(function(resolve,reject){
var i = 0,
result = [],
len = promises.length;
function resolver(index) {
return function(value) {
resolveAll(index, value);
};
}
function rejecter(reason){
reject(reason);
}
function resolveAll(index,value){
result[index] = value;
if(index == len - 1){
resolve(result);
}
}
for (; i < len; i++) {
promises[i].then(resolver(i),rejecter);
}
});
}
4 回复
经自测发现代码逻辑确实有问题 测试代码:
var a = Promise.resolve(1);
var b = Promise.delay(2000, 2);
var c = Promise.delay(1000, 3);
var d = Promise.resolve(4);
var e = Promise.resolve(5);
Promise.all([a,b,c,d,e]).then(function(result) {
console.log(result);
});
测试结果: /usr/local/bin/node promise.js [ 1, , , 4, 5 ]
Process finished with exit code 0