Reputation: 363
How do i get the value of myObject.myname, myObject.myage from the function getval? It returns undefined when i console.log it. Btw I'm using node js. Thanks.
var post = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (data) {
console.log('Response: ' + data);
var myObject = JSON.parse(data);
console.log('----------------------------------------------');
console.log(myObject.myname);
console.log(myObject.myage);
console.log('----------------------------------------------');
});
});
function getVal() {
//some code here
console.log(myObject.myname);
console.log(myObject.myage);
}
Upvotes: 1
Views: 3100
Reputation: 943100
myObject
outside the anonymous function you pass to request
(var myObject
) instead of inside it. At present it is a local variable.getVal()
after the HTTP response has been received (otherwise it won't have been set yet). At present you aren't calling it at all.Upvotes: 2
Reputation: 5749
There is a scope issue, can you try this instead?
var myObject = {};
var post = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (data) {
console.log('Response: ' + data);
myObject = JSON.parse(data);
console.log('----------------------------------------------');
console.log(myObject.myname);
console.log(myObject.myage);
console.log('----------------------------------------------');
});
});
function getVal() {
//some code here
console.log(myObject.myname);
console.log(myObject.myage);
}
Upvotes: 0