如果您真的只是想知道一堆异步操作何时完成,那么有多种方法可以解决问题。
一种方法是简单地记录所有异步操作何时完成,然后在该计数达到其最终值时执行您想要的任何操作:
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 以使其支持承诺,那么promises 是一种更现代的方式,可以在一个或多个异步操作完成时获得通知。这是一个承诺的实现:
首先,promisify 异步操作:
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 就是这样一个库。