node.jshttprequestlocaljson-web-token

How can I assign global and local variables in node js


If I declare a variable and assign value from a method and print outside the method.But it shows undefined. My code is,

var value;
var getValue = function getValue(){
    value = 5;
};
console.log(value); 

Output,

undefined

I am also trying in global variable

var getValue = function getValue(){
    global.value = 5;
};
console.log(value);

But shows some errors,

console.log(value);
            ^

ReferenceError: value is not defined
    at Object.<anonymous> (~/MyApp/test.js:8:13)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Function.Module.runMain (module.js:447:10)
    at startup (node.js:146:18)
    at node.js:404:3

Solution

  • Your problem is that you don't wait for the callback to be executed.

    Instead of

    app.post('/authenticate', function(req, res) {
        var userToken;
        ...
        amqHandler.reciveData(amqpConnection ,function(err,data){
            if(!err){
                httpRequestHandler. makeHttpRequest(data, function(err,userToken){
                    global.apiResponce = JSON.parse(userToken).token;
                    global.convertedObjects = JSON.stringify(apiResponce);
                    console.log("convertedObjects==>"+convertedObjects);
                    userToken = {token:JSON.stringify(apiResponce)};
                });
            }
        });
        res.send({msg:userToken}); // this is executed before the end of reciveData
    });
    

    You must send the response from the callback passed to the asynchronous function:

    app.post('/authenticate', function(req, res) {
        ...
        amqHandler.reciveData(amqpConnection ,function(err,data){
            if(!err){
                httpRequestHandler. makeHttpRequest(data, function(err,userToken){
                    global.apiResponce = JSON.parse(userToken).token;
                    global.convertedObjects = JSON.stringify(apiResponce);
                    console.log("convertedObjects==>"+convertedObjects);
                    var userToken = {token:JSON.stringify(apiResponce)};
                    res.send({msg:userToken}); // <=== send here
                });
            }
        });
    });
    

    Note that there are constructs, most notably promises which make it easier to chain asynchronous calls. But you must first understand the problem and see how you can handle it with callbacks.