0

我找到了这个如何实现 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

4

2 回答 2

2
let results = [], i;

相当于

let results = [];
let i;
于 2021-10-13T16:13:57.823 回答
1
let results = [], i;

等同于:

let results = [];
let i;

我得到了价值undefined。undefined 上NaN的任何数学运算都不会返回数字。

console.log(undefined + 1);

于 2021-10-13T16:16:55.573 回答