JavaScript for循环内的asynchronous函数

我试图从数据库中获取数据到一个jsonvariables,然后将其发送到客户端,问题是,因为我从数据库中asynchronous获取所有数据,我不知道什么时候json被正确填充。

var geojson={ "type": "FeatureCollection", "features": [] }; var routeObjects=JSON.parse(route.route); for(var i=0;i<routeObjects.length;i++){ hostelery.getInfo(routeObjects[i].ID, function(err, hostelery){ if(!err) geojson.features.push(hostelery); }); } 

所以,当所有的数据在geojson中,我想把它发回客户端…

任何帮助,将不胜感激…

非常感谢你。

如果你真的只是想知道什么时候完成了一堆asynchronous操作,有多种方法可以解决这个问题。

一种方法是在所有的asynchronous操作完成时保持计数,然后在计数达到其终值时执行任何您想要的操作:

 var geojson = { "type": "FeatureCollection", "features": [] }; var doneCount = 0; var routeObjects = JSON.parse(route.route); for (var i = 0; i < routeObjects.length; i++) { hostelery.getInfo(routeObjects[i].ID, function (err, hostelery) { if (!err) geojson.features.push(hostelery); ++doneCount; if (doneCount === routeObjects.length) { // all async operations are done now // all data is in geojson.features // call whatever function you want here and pass it the finished data } }); } 

如果您的API支持承诺,或者您可以“promisify”API以使其支持承诺,那么承诺是在一个或多个asynchronous操作完成时获得通知的更现代的方式。 这是一个承诺的实现:

首先,提出asynchronous操作:

 hostelery.getInfoAsync = function(id) { return new Promise(function(resolve, reject) { hostelery.getInfo(id, function(err, data) { if (err) return reject(err); resolve(data); }); }); } 

那么,你可以用Promise.all()

 var geojson = { "type": "FeatureCollection", "features": [] }; var routeObjects = JSON.parse(route.route); Promise.all(routeObjects.map(function(item) { return hostelery.getInfoAsync(item.ID).then(function(value) { geojson.features.push(value); }).catch(function(err) { // catch and ignore errors so processing continues console.err(err); return null; }); })).then(function() { // all done here }); 

由于它看起来像使用node.js,因此还有许多asynchronous库提供了用于pipe理asynchronous操作的各种function。 Async.js就是这样一个库。