我找到了这个如何实现 Promise.all 方法的例子。
function all(iterable){ // take an iterable
// `all` returns a promise.
return new Promise(function(resolve, reject){
let counter = 0; // start with 0 things to wait for
let results = [], i;
for(let p of iterable){
let current = i;
counter++; // increase the counter
Promise.resolve(p).then(function(res){ // treat p as a promise, when it is ready:
results[i] = res; // keep the current result
if(counter === 0) resolve(results) // we're done
}, reject); // we reject on ANY error
i++; // progress counter for results array
}
});
}
我不确定这行代码发生了什么:let results = [], i;
当我在控制台中运行它时,我变得未定义。在所有函数中,他们正在执行 i++,但是在未定义的值上使用该运算符变成了 NaN。这里发生了什么?如果 'i' 未定义,他们如何将其用作数组的索引results[i] = res; // keep the current result
?