I'm struggling with asynchronous events in Node.js.
My app is doing a first HTTP GET request and then based on some information found in the body of the response it is looping a certain amount of times.
At each iteration it calls a function which sends other HTTP GET requests and returns a result pushed in the elements array.
My problem is that I want to console.log() the elements array when all the http requests are done. Here's my code :
http.get('mysite.com', function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
var last = 5,
elements = [];
for(var i=0; i < last; i++) {
elements.push(myRequest(i));
}
console.log(elements);
// Do some stuff with the elements array after it has been populated
});
}).on('error', function(error) {
console.log(error);
});
var myRequest = function(i) {
http.get('mysite.com/page' + i, function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
// Do parsing here
return parsed;
});
}).on('error', function(error) {
console.log(error);
});
};
I thought about using the async module but I'm not sure how to use it in this use case.
Thanks in advance !