javascript for循环内的异步函数 [英] Asynchronous function inside a javascript for loop
问题描述
我正在尝试将从数据库中获取的数据插入json变量,然后将其发送到客户端,问题是当我异步地从数据库获取所有数据时,我不知道json是何时正确填充.
I am trying to insert data that I get from the database to a json variable and then send it to the client, the problem is that as I get all the data from the database asynchronously I don't know when the json is correctly filled.
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中时,我想将其发送回客户端...
So when all the data is in the geojson I would like to send it back to the client...
任何帮助将不胜感激...
Any help would be appreciated...
非常感谢您.
推荐答案
如果您实际上只是想知道何时完成一堆异步操作,则有多种方法可以解决此问题.
If what you're really just trying to do is to know when a bunch of async operations are done, there are multiple ways to approach the problem.
一种方法是简单地对所有异步操作何时完成进行计数,然后在该计数达到其最终值时执行您想要执行的任何操作:
One way is to simply keep a count for when all the async operations have completed and then carry out whatever operation you want to when that count reaches its terminal value:
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支持承诺,或者您可以承诺化" API以使其支持承诺,则
If your API supports promises or you can "promisify" the API to make it support promises, then promises are a more modern way to get notified when one or more async operations are complete. Here's a promise implementation:
首先,承诺异步操作:
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,因此还有许多异步库提供了用于管理异步操作的各种功能. Async.js 是这样的一个库.
Since it looks like you're using node.js, there are also numerous async libraries that offer various features for managing async operations. Async.js is one such library.
这篇关于javascript for循环内的异步函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!