I am new to Node, using the "request" module in NodeJS to get data from some urls. The code is not working due to the asynchronization of requests, would closure / callback be able to solve it?
A brief version of my code:
var request = require('request');
var urlList = ["http://a", "http://b", "http://c"];
for (var i = 0; i < urlList.length; i++) {
var result = processURL(urlList[i]);
console.log(result); // output "[]" rather than actual results.
}
function processURL(url) {
//..Do some pre processing on url
var tempResult = [];
request(url, function(error, response, json){
tempResult.push(json); //There is more processing here, but just to make code easier to read I pushed the entire json response.
});
return tempResult;
}
I am pretty sure the trouble's with the way I deal with the "tempResult" but not sure how to resolve (maybe with callback?). Any suggestions would help! Thanks.