更新时间:2022-06-02 22:29:00
如果您实际上只是想知道何时完成一堆异步操作,则有多种方法可以解决此问题.
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.