Reputation: 3175
My requirement is that I need to load JSON data from multiple REST resources. For this I need to make multiple get requests. I need to perform some function when all the requests have been completed.
Below is my code:
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");
}
The issue I am facing is that the allDataLoaded
function is not called, although the dataLoaded
functions are being called correctly.
I am using request-json and async npm packages for this. Thanks for your time, please let me know if any other information is required.
Upvotes: 2
Views: 51
Reputation: 664196
async.parallel
passes a callback to every task which you need to call, otherwise it cannot know when your task has finished. Use
var asyncTasks = urls.map(function (item) {
return function (cb) {
// ^^
client.get(item, function (err, res, body) {
dataLoaded(err, res, body)
cb(err);
// ^^^^^^^
});
};
});
then async.parallel(asyncTasks, allDataLoaded)
will work.
Upvotes: 4