函数中的项目未推送到数组

Item in function not pushing to array

我在应用程序中有一段代码无法将项目推送到空数组。在本节的开头,我创建了一些空数组变量。

var sumPOP = [];
var sumRACE = [];
var sumLANG = [];
var sumINCOME = [];

然后我将遍历一些选定的数据,所以我有一个 for 循环。在这个循环中,我正在调用 api(我知道,这是 GIS。那是无关紧要的。假装它是一个 ajax 调用)来检索一些数据。我能够 console.log() 数据并正确显示。然后我想将该数据(循环中的每个项目)推送到前面提到的空数组。然后为了测试数组是否已填充,我 console.log() 数组,在循环内和循环外。我的问题是当我 console.log 数组时没有任何显示。为什么数据没有被推到阵列之外?注意:调用函数 (esriRequest) 中的 console.log(sumPOP) 运行 确实显示了推送到数组的项目:

for (var i=0;i<results.features.length;i++){
            ...
    esriRequest({
        url:"https://api.census.gov/data/2016/acs/acs5",
        content:{
          get: 'NAME,B01003_001E,B02001_001E,B06007_001E,B06010_001E',
          for: `tract:${ACS_TRCT}`,
          in: [`state:${ACS_ST}`,`county:${ACS_CNTY}`]
        },
        handleAs:'json',
        timeout:15000
        }).then(function(resp){
          result = resp[1];
          POP = result[1];
          console.log(POP);
          sumPOP.push(POP);
          RACE = result[2];
          LANG = result[3];
          INCOME = result[4];
          console.log('POP: ' + POP + ', RACE: ' + RACE + ', LANG: '+ LANG + ', INCOME: ' + INCOME);
        }, function(error){
          alert("Data failed" + error.message);
        });
        console.log('POP: ' + sumPOP);
     ...
    }
console.log('POP: ' + sumPOP); 

补充说明:我最终的目标是在对选中的数据进行迭代后得到最终的数组,并进行汇总;或者更确切地说,将它们加在一起。我预期的数组结果是 sumPOP = [143, 0, 29, 546, 99]; 我想应用一个函数(也在循环之外)来做到这一点:

newSum = function(category) { 
    let nAn = n => isNaN(n) ? 0 : n;  //control for nonNumbers
    return category.reduce((a, b) => nAn(a) + nAn(b))
  };

...然后 运行 popTotal = newSum(sumPOP); 得到总数。

我相信你的数据被推送了,只是看起来这不是因为你的console.log()

的位置

由于您正在处理一个异步 api 调用,唯一可以保证您拥有数据的地方是在您的 .then() 函数中 。本质上,在您调试时,如果您在所有 console.log 处添加断点,您会注意到它首先触发 .then() 之外的断点,最后触发 .then() 内的断点。由于该顺序,您的阵列似乎没有将数据推送给它们。

我在下面的示例代码中添加了一些注释,以说明您应该在哪里看到数据。

编辑:我也做了一个小调整,所以所有的数组都会被填充

编辑 2:修改代码,使其以 "synchronous" 方式处理多个异步承诺

var sumPOP = [];
var sumRACE = [];
var sumLANG = [];
var sumINCOME = [];
var myPromises = []; // added this new array for promise.all

for (var i = 0; i < results.features.length; i++) {
  var myPromise = esriRequest({
    url: "https://api.census.gov/data/2016/acs/acs5",
    content: {
      get: 'NAME,B01003_001E,B02001_001E,B06007_001E,B06010_001E',
      for: `tract:${ACS_TRCT}`,
      in: [`state:${ACS_ST}`, `county:${ACS_CNTY}`]
    },
    handleAs: 'json',
    timeout: 15000
  });
  myPromises.push(myPromise);

  // because you are making an async request, at this point, sumPOP may be empty
  console.log('POP: ' + sumPOP);
}

Promise.all(myPromises).then(function(resp) {
  result = resp[1];
  POP = result[1];
  console.log(POP); // this will show POP with data


  RACE = result[2];
  LANG = result[3];
  INCOME = result[4];

  sumPOP.push(POP);
  sumRACE.push(RACE); // added this to populate array
  sumLANG.push(LANG); // added this to populate array
  sumINCOME.push(INCOME); // added this to populate array

  // at this point, all your arrays should have data
  console.log('POP: ' + POP + ', RACE: ' + RACE + ', LANG: ' + LANG + ', INCOME: ' + INCOME);
  
  // now that this you have all values, you can call your outside function
  this.handleData();
}, function(error) {
  alert("Data failed" + error.message);
});

// because you are making an async request, at this point, sumPOP may be empty
console.log('POP: ' + sumPOP);

var handleData = function() {
  // do something with the completed data
}