2

I have a function like this inside a NodeJs app

function dojob(url){
var resultList = [];
request (url, function (error, response, html){
    if(!error){
        var $ = cheerio.load(html);
        $(".elements a").each(function(i, el){
            resultList.push($(this).text()); //$(this).text() have values!!
        });
    }
});
return resultList; //but here it is empty
}

Now resultList will be always empty [], and return empty, how to work around this.

MHMr
  • 119
  • 1
  • 2
  • 1
    https://jsfiddle.net/arunpjohny/a02q7w3b/1/ – Arun P Johny Aug 20 '15 at 13:32
  • The issue here is that your resultList list is being returned before the request comes back because request calls are asynchronous. You have many options to handle this situation but the simplest is shown in @arun 's fiddle, by passing a callback to doJob, and putting it inside the request callback handler. Note you are soon going to enter callback hell and may want to look into a control flow library. – RadleyMith Aug 20 '15 at 14:15

0 Answers0