0

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.

Shawn Xu
  • 163
  • 4
  • Welcome to the wonderful world of **async**! You can't do that. You need to return a promise or accept a callback. – SLaks Nov 23 '14 at 03:28
  • Welcome to [so]. It appears that your question is the same as [How to return value from an asynchronous callback function?](http://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function) Please take a look at that and see if it answers your question. Thanks! – Qantas 94 Heavy Nov 23 '14 at 03:33
  • @Qantas94Heavy yes the second link definitely helps a lot. Thanks! Should I delete this question or something? – Shawn Xu Nov 23 '14 at 19:57
  • @SLaks sounds like a lot of pain! – Shawn Xu Nov 23 '14 at 19:58

0 Answers0