Reputation: 552
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
Upvotes: 0
Views: 19615
Reputation: 382132
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.
Upvotes: 1
Reputation: 351
In your first example, value is set in the function but the function is never called. Therefore value is undefined
.
In the global example, value is never declared and thus not defined.
What you want to do is call getValue() and then output your value to the console.
First example:
var value;
var getValue = function(){
value = 5;
};
getValue();
console.log(value); // should return 5
Global example:
var global = {}; // create an object otherwise you get a 'global is not defined' error
var getValue = function getValue(){
global.value = 5;
};
getValue();
console.log(global.value); // should return 5
Upvotes: 4
Reputation: 12437
Your function isn't being run, therefore value is not being set.
var value;
var getValue = function getValue(){
value = 5;
};
getValue(); // call function to set value of 'value'
console.log(value);
Upvotes: 2