I have a question about the async package in nodejs.
Essentially, what i have is an array of objects in which each element contains information that i need to form a xmlhttprequest to a remote server. So i thought i could use async.forEach to fire the requests in sequence, store the results in a variable and use them later in my code.
Here is the sample code:
async.series([
function(callback)
{ //async.series element 1
async.forEach(req_info_arr, function(req_info_element, callback) {
var url = ... //form the url using the info from req_info_element
var req = new XMLHttpRequest();
req.open("GET", url, true);
req.send(); //fires the request
req.onload = function() {
//do stuff
callback();
}//end of onload
req.onerror = function() {
//do stuff
callback(err);
}
}/*end of async_forEach */, callback);
callback();
},
function(callback){
//async.series element 2
//do stuff...want this to be done only after we have received a response for every request fired in async.series element 1
}
], function(err) {
});
What happens is this: async.forEach goes over each element in req_info_arr, fires the request for each element.
Once done. this reaches the second element in async.series. But i have not yet received a response for the xhr's fired in async.series element 1, so my code fails.
Is there a solution for this problem? Have i misunderstood anything?
Any help/pointers are appreciated.
I guess it's because of the callback(); right below the async.forEach, this triggers the next step in the series immediately:
.
.
.
}/*end of async_forEach */, callback);
callback(); //<-- remove this guy
That's because you are calling the first async.series() callback right after the async.forEach() block.
You need to remove that callback(); on line 21.