这个想法是多次运行地理编码(针对数组)。为了循环异步函数,我决定使用递归方式。
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);
});
作为一个额外的好处,所有异步操作都是并行完成的。
关于javascript - 使用递归进行异步循环: How to access push array data?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36627341/