通过 JSON 的迭代依赖于异步调用

Iteration through JSON dependent on asynchronous calls

我正在尝试创建一个 promise 函数,它将迭代一个 geoJSON 对象,使用一个 URL-esque 属性 存储在一个占位符值 属性 调用存储在该地址的数据。 JSON 迭代本身是功能性的,但我似乎无法得到正确计时的主要承诺,它在我的值实际引入之前返回已解决。

    //Here is one feature in my geoJSON object
    {
    "type": "Feature",
    "properties": {
      "name": "AC4",
      "url": "/*Removed*/",
      "values": {
        "DA_T": {
          "ORD": "station:|slot:/Drivers/NiagaraNetwork/S_1563/B_1964/B1964_SSC2/points/AC4/MixedAirTemp",
          "value": "placeholder",
        }
      }
    },
    "geometry": {
      "type": "Polygon",
      "coordinates": [
        [
          [102.0,-59.0],
          [102.0,-73.5],
          [67.5,-73.5],
          [67.5,-59.0]
        ]
      ]
    }},



  //This is what I currently have for my iterating function
  function jsonValueFill(json, valueName) {
    return new Promise (function(resolve, reject){
      var i = 0;
      var k = json.features.length;
      while (i<k) {
        console.log('iteration: ' + i)
        if (json.features[i].properties.values.valueName != undefined){
          numFromPoint (json.features[i].properties.values.valueName.ORD)
          .then(function(output){
            json.features[i].properties.values.valueName.value = output
          });
        };
      i++;
      if(i == k) {resolve(json)}
      }
    })
  };

numFromPoint 是我创建的一个 promise 函数,用于从称为 ORD 的内部地址中提取值,并且我已确认它按预期工作。但是,即使在我遍历对象之后添加 setTimeout(function(){console.log(testJson)}, 6000) 来检查对象的状态,也没有设置值 属性 .

我觉得可以再简单一点:

function jsonValueFill(json, valueName) {
  const promises = json.features.map(feature => {
    if (feature.properties.values[valueName] !== undefined) {
      return numFromPoint(feature.properties.values[valueName].ORD)
        .then(function(output) {
          feature.properties.values[valueName].value = output
        })
    }
  })

  return Promise.all(promises).then(() => json)
}
while (i<k) {
    console.log('iteration: ' + i)
    if (json.features[i].properties.values.valueName != undefined){
      numFromPoint (json.features[i].properties.values.valueName.ORD)
      .then(function(output){
        json.features[i].properties.values.valueName.value = output
      });
    };
  i++;

看到这段代码,numFromPoint解析时i的值和启动时不一样。在循环中调用 promise 也不是一个好主意。在闭包中抽象出来。