Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use request module to retrieve JSON and return value

I use this request module to make HTTP request in Nodejs

Sample code:

module.exports.getToken = function(){
    var token ;

    request(validLoginRequest, function(err,resp,body){
        var json = JSON.parse(JSON.stringify(body));
        console.log("from request(): token=" + json.accesstoken);
        token = json.accesstoken;
    });

    console.log("getToken() returns:" + token);
    return token;
}

But the token is always undefined. What did I do wrong?

like image 778
Dio Phung Avatar asked Dec 12 '25 03:12

Dio Phung


1 Answers

You've fallen into the classic node asynch trap. The code in the top level function of your module will return before the callback in the inner request function happens. token is not yet defined when you return it.

The simplest solution would be to pass a callback down from the outer function and call it from the callback returned to the request function. If that's not satisfying you could use the $q library to return a promise or find a module that will do synchronous http calls.

like image 87
Robert Moskal Avatar answered Dec 13 '25 23:12

Robert Moskal