【问题标题】:Cannot access array elements outside for loop无法访问 for 循环外的数组元素
【发布时间】:2020-08-24 17:25:41
【问题描述】:

问题:

  • 当我尝试控制台记录循环内的数组时,它显示结果已添加到数组中。但是,当在循环之外时,我在 console.log 上得到一个空数组
var ResultArray01=  [];
for(var gg=0; gg<ResultArray.length;gg++)   // ResultArray is come from another function
{
  IPFS.get.call(ResultArray[gg],function(error, result) {      //this function is about smart contract
  if (error) 
  {
    console.log(error);
  }
  else
  {
    ResultArray01[gg] = result;    //get the result, and store it into ResultArray01
    console.log(ResultArray01[gg]);    //it can successfully print the value
  }
  });

}
console.log(ResultArray01);    //returns empty array

有人可以帮助我吗?谢谢

【问题讨论】:

  • 将for循环改为使用let关键字而不是var,因为当回调函数被执行时,gg会因为闭包而超出数组的范围,例如:for(let gg=0; gg&lt;ResultArray.length;gg++)
  • 您的回调是非阻塞和异步的。这意味着您的 console.log(ResultArray01) 在回调之前运行。如果要查看ResultArray01 的值,请将console.log(ResultArray01) 放在回调中。那是您可以使用该值的唯一地方。这就是 node.js 中异步编码的工作方式。你在回调中继续你的代码流,而不是在回调之后。
  • 感谢您的回答,因为我想将 ResultArray01 中的值渲染到 HTML 页面,似乎渲染无法将其放入 for 循环中。我怎样才能达到它?谢谢

标签: javascript arrays node.js for-loop


【解决方案1】:

正如评论中提到的@jfriend00。您在执行回调之前的console.log()。您可以在此处使用promises 来处理这种情况。 这样才能达到预期的效果。

var ResultArray01 = [];
var promises = [];
for (var gg = 0; gg < ResultArray.length; gg++) {
  promises.push(
    new Promise((resolve, reject) => {
      IPFS.get.call(ResultArray[gg], function (error, result) {
        if (error) {
          console.log(error);
          // reject promise in case there is any error.
          reject(error)
        } else {
          //get the result, and store it into ResultArray01
          ResultArray01[gg] = result;
          // it can successfully print the value
          console.log(ResultArray01[gg]); 
          // resolve if everything is as expected.
          resolve();
        }
      })
    }) 
  );
}
Promise.all(promises).then(() => {
  console.log(ResultArray01); // it should print the desired result now.
}).catch((err) => console.log(err))

【讨论】:

  • 太棒了。有人也可以让我们知道使用这种方法对性能的影响吗?任何其他方式来做 console.log?
猜你喜欢
  • 2019-08-11
  • 1970-01-01
  • 2021-05-13
  • 2020-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多