Anshuman Jasrotia Anshuman Jasrotia - 1 year ago 100
Node.js Question

Multiple get requests with request-json not executing properly with async in node js

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

function dataLoaded(err, res, body) {
console.log('Data Loaded');

function allDataLoaded() {
console.log("All data loaded");

The issue I am facing is that the
function is not called, although the
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.

Answer Source

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 = (item) {
    return function (cb) {
//                   ^^
        client.get(item, function (err, res, body) {
            dataLoaded(err, res, body)
//          ^^^^^^^

then async.parallel(asyncTasks, allDataLoaded) will work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download