Use request module to retrieve JSON and return value

I use this requestmodule to make an HTTP request in Nodejs

Code example:

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 tokenalways undefined. What have I done wrong?

+3
source share
2 answers

You are trapped in the classic node node trap. The code in the top-level function of your module will return before a callback occurs in the internal request function. the token is not yet defined when you return it.

, . , $q, , HTTP-.

+6

@Robert Moskal.

module.exports.getToken = function(callback){

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

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

All Articles