Xfoguet
Xfoguet

Reputation: 75

nodejs return variable from request

I'm using express.

From a controller, I call a function that makes a request to an URL and retrives a HTML tag (with cheerio). I'm not able to return that value even that all console.logs work.

Code:

router.get('/', function(req, res) {
    var data = "none";
    var newData = parse(data);

    console.log(newData);
})



function parse(out){
    {
        url = 'http://www.XXXXXX.int/';
        out =  out || "Init value";
        request(url, out,  function(error, response, html){
            console.log(out);
            out ="ASDA";
            return out; //op1
        }) ;
        return out; //op2
    }

}

I'm able to retrive the title var. But the return's (even inside request) return don't modify original's value. It might be something about synchrony.. but i'm really lost..

Any light?¿

Upvotes: 0

Views: 6513

Answers (1)

VirginieLGB
VirginieLGB

Reputation: 548

Requests are made asynchronously. You need to add a callback, which is standard Node.JS architecture

router.get('/', function(req, res) {
    var data = "none";
    var newData = "";
    parse(data , function( val ) {
         newData = val;
         console.log( "newData : " , newData );
         console.log( "this happens last" );
         // if you need to return anything, return it here. Do everything else you want to do inside this parse function.
         return res.sendStatus( 200 );
    } );
    console.log( "this happens first" );
});

function parse( out , callback ){
    url = 'http://www.XXXXXX.int/';
    out =  out || "Init value";
    request(url, out,  function(error, response, html){
        // don't you do anything with the error, response, html variables?
        console.log( "out : " , out);
        out ="ASDA";
        return callback( out ); //op1
   }) ;
}

Doing that, your output should be:

this happens first
out :  none
newData :  ASDA
this happens last

Upvotes: 3

Related Questions