I am working with javascript for quite some time now and recently started using Nodejs in my project. I have a requirement to make some http calls from my nodejs app and then when all of them are done, need to consolidate and send the response.
In this regards, I was searching and came across async module for Nodejs. (https://github.com/caolan/async)
I also found a blog which nicely explains how to use this feature. (http://justinklemm.com/node-js-async-tutorial/)
The below code snippet is what I am planning to use for my task.
// Include the async package
// Make sure you add "async" to your package.json
async = require("async");
// 1st para in async.each() is the array of items
async.each(items,
// 2nd param is the function that each item is passed to
function(item, callback){
// Call an asynchronous function, often a save() to DB
item.someAsyncCall(function (){
// Async call is done, alert via callback
callback();
});
},
// 3rd param is the function to call when everything's done
function(err){
// All tasks are done now
doSomethingOnceAllAreDone();
}
);
In the above I need to make http call instead of item.someAsyncCall section. Specifically the code that I have is
var formaatedResponse=[];
request("http://" + API_HOST + "/app/v1/customers/" + element,
function (error, response, body) {
console.log('Ajax call response');
formaatedResponse.push(JSON.parse(response.body));
});
How to accommodate my changes since when I tried adding the above code it does not work as intended.
My code:
function consolidateResponse(){
console.log("Everything is done.");
console.log(formaatedResponse);
}
// 1st para in async.each() is the array of items
async.each(result,
// 2nd param is the function that each item is passed to
function(element, callback){
// Call an asynchronous function, often a save() to DB
request("http://" + API_HOST + "/app/v1/customers/" + element, function (error, response, body) {
console.log('Ajax call response');
formaatedResponse.push(JSON.parse(response.body));
});
callback();
},
// 3rd param is the function to call when everything's done
function(err){
// All tasks are done now
consolidateResponse();
}
);
Regards, Pradeep
http requestsare fired in parallel, and thats whatasyncdoes. It will not wait for it to end.consolidateResponse()will be called after all the requests are fired