Joenel de Asis
Joenel de Asis

Reputation: 363

Node.js access the value of variable from another function

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

Answers (2)

Quentin
Quentin

Reputation: 943100

  1. Declare myObject outside the anonymous function you pass to request (var myObject) instead of inside it. At present it is a local variable.
  2. Call 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

Emilio Rodriguez
Emilio Rodriguez

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

Related Questions