今天看网上关于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);
}
});
}