returning undefined before data -- callback implemented --please help

61 views
Skip to first unread message

wasiu razak

unread,
Dec 2, 2015, 9:08:21 AM12/2/15
to nodejs
am trying to grab data from a function , by passing in a args and return data 
but when i run i get undefined before i get the data , i have wrapped it in a time still same output 
version 2

function citifmonlineDetail(url, callback) {

setTimeout(function() {
request(url, function(error, response, html) {

var detail = "";

if (!error) {
$ = cheerio.load(html);

$('.entry p').each(function(index, paragraphs) {
console.log($(paragraphs).text());
var a = $(paragraphs).text();
detail = detail.concat(a + " ");
});

callback(detail);
}


});
}, 3000);
}

var data= citifmonlineDetail(citi,function(result) {
return result;
}) ;
console.log(data);


version 1

function citifmonlineDetail(url) {
request(url, function(error, response, html) {
    if (!error) {
        $ = cheerio.load(html);
        var b;

        $('.entry p').each(function(index, paragraphs) {
            var a =$(paragraphs).text();
            b =b.concat(a);

        });
        return b 
    }
});
}

Mohan Kumar

unread,
Dec 2, 2015, 11:56:23 PM12/2/15
to nodejs

  HI Wasiu ,

  The problem you are facing is the async behaviour of JavaScript.

  when the function 
citifmonlineDetail(citi,function(result) {
return result;
}) ; 

is called  the function directly returns undefined , since the function not containing  return statement.

There are two ways to solve 
1) simply changing to 
var data ;
citifmonlineDetail(citi,function(result) {
data =  result;
        console.log(data);
}) ;

2)  BY using promise 

 
var promise = new Promise(function(resolve) {
  // do a thing, possibly async, then…
    function hello(){
       setTimeout(function(){
          debugger;
          resolve("hello");

       },1000)
    };
    hello();

});

promise.then(function(val){
     data = val;
     console.log(data);
  });




   

wasiu razak

unread,
Dec 3, 2015, 9:30:07 AM12/3/15
to nodejs
thanks so much , guess i still need to revisit callbacks and promises ,though i understood it , thanks again 

Zlatko

unread,
Dec 4, 2015, 10:04:24 AM12/4/15
to nodejs
On Thursday, December 3, 2015 at 3:30:07 PM UTC+1, wasiu razak wrote:
thanks so much , guess i still need to revisit callbacks and promises ,though i understood it , thanks again 




We all think we understand them, and we all often fail :) That's why it's called callback hell.

 
Reply all
Reply to author
Forward
Message has been deleted
0 new messages