我的要求是我需要从多个REST资源加载JSON数据。为此,我需要发出多个get请求。当所有请求都完成后,我需要执行一些功能。
下面是我的代码:
var asyncTasks = [];
//These URLs are dynamic and can increase or decrease
var urls = ["resource1", "resource2", "resource3"];
var client = request.createClient("domainurl");
urls.forEach(function (item) {
asyncTasks.push(function () {
client.get(item, function (err, res, body) {
dataLoaded(err, res, body)
});
});
});
async.parallel(asyncTasks, function () {
// All tasks are done now
allDataLoaded();
});
function dataLoaded(err, res, body) {
console.log('Data Loaded');
};
function allDataLoaded() {
console.log("All data loaded");
}
我面临的问题是allDataLoaded
尽管dataLoaded
正确调用了函数,但未调用函数。
我为此使用request-json和async npm包。感谢您的宝贵时间,如果需要其他任何信息,请告诉我。
async.parallel
将回调传递给您需要调用的每个任务,否则它将不知道您的任务何时完成。用
var asyncTasks = urls.map(function (item) {
return function (cb) {
// ^^
client.get(item, function (err, res, body) {
dataLoaded(err, res, body)
cb(err);
// ^^^^^^^
});
};
});
然后async.parallel(asyncTasks, allDataLoaded)
会工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句