异步循环使用递归:如何访问推送数组数据

Use recursion for async loop: How to access push array data?

本文关键字:访问 数据 数组 何访问 循环 递归 异步      更新时间:2023-09-26

这个想法是多次运行地理代码(针对数组)。为了循环一个异步函数,我决定使用递归方式。

var geocoder = require('geocoder')
var geocoded = []
//Example array
var result = [{
  'company_no': 'A',
  'address': 'a'
}, {
  'company_no ': 'B',
  'address': 'b'
}]
function geocodeOneAsync(result, callback) {
  var n = result.length
  function tryNextGeocode(i) {
    if(i >= n) {
      //onfailure("alldownloadfailed")
      return
    }
    var address = result[i].address
    geocoder.geocode(address, function (err, data) {
      geocoded.push(result[i].company_no)
      console.log('data1' + JSON.stringify(
          geocoded)) //Result is ==> data1["A"], data1["B"]
      tryNextGeocode(i + 1)
      //  }
    })
  }
  console.log('data1' + JSON.stringify(geocoded))
  tryNextGeocode(0)
}
geocodeOneAsync(result, function () {
  JSON.stringify('data final ' + geocoded) // result is  empty []. I want to access the final geocoded array?
})

基本上是我如何才能得到最终值的问题。

为此,最简单的方法是使用映射和Promise,而不是递归。

function geocodeOneAsync(result, callback) {
    // with map you get an array of promises
    var promises = result.map(function (company) {
        return new Promise(function (resolve, reject) {
            var address = company.address;
            geocoder.geocode(address, function (err, data) {
                if(err) {
                    reject(err);
                }
                resolve(company.company_no);
            });
        }).catch(function(error) {
            // you can handle error here if you don't want the first occuring error to abort the operation.
        });
    });
    // then you resolve the promises passing the array of result to the callback.
    Promise.all(promises).then(callback);
}
geocodeOneAsync(result, function (geocodedArray) {
    // here geocoded is ['A','B']
    JSON.stringify(geocodedArray);
});

额外的好处是,所有异步操作都是并行进行的。

如果这不能回答您的问题,我深表歉意。我认为您需要在递归终止条件下调用回调:

if ( i >= n ) {
    callback();
}

完整代码(我为自己修改了它):

var geocoder = require('geocoder');
var geocoded = [];
function geocodeOneAsync(result, callback) {
    var n = result.length;
    function tryNextGeocode(ii) {
        if (ii >= n ) {
            //onfailure("alldownloadfailed")
            callback();
            return;
        }
        var address = result[ii].address
        geocoder.geocode(address, function (err, data) {
            geocoded.push(result[ii].company_no);
            console.log('data1' + JSON.stringify(geocoded)); //Result is ==> data1["A"], data1["B"]_++
            console.log("n=" +n + ",ii=" + ii);
            tryNextGeocode(ii + 1);
        });
    }
    console.log('data1' + JSON.stringify(geocoded));
    tryNextGeocode(0);
};
//Example array
var result = [
    {'company_no': 'A,','address': 'a'},
    {'company_no': 'B', 'address': 'b'}
];
geocodeOneAsync(result, function () {
     console.log(JSON.stringify('data final ' + geocoded)); // result is  empty []. I want to access the final geocoded array?
});

我得到的输出是:

data1[]
data1["A,"]
n=2,ii=0
data1["A,","B"]
n=2,ii=1
"data final A,,B"

希望能有所帮助!