0

Have a following node.js call to http get REST API. When I run it, it returns the JSON result. However, I am trying to get the result to console.log on var r after assigning the result. Why do I always get undefined? Looks like I am messing up the javascript scope. Any help is appreciated.

var http = require('http'), 
    oex_appId = 'myappId',
    _hostname = 'openexchangerates.org',
    _path = '/api/latest.json?app_id=' + oex_appId;

var r;

function getRates(cb) { 
var options = {
        hostname: _hostname,
        path: _path,
        method: 'GET'
    };

var responseCallback = function(response) {
    var latestRates = '';

    var parseCurrencies = function(rates) {
        var currencies = JSON.parse(rates);
        currencies.rates['USD'] = 1;
        return currencies.rates;
    };

    response.setEncoding('utf8');
    response.on('data', function(chunk) {
        latestRates += chunk;
    }).on('error', function(err) {
        throw new Error(err);
    }).on('end', function() {
        cb(parseCurrencies(latestRates));
    });
};  

var req = http.request(options, responseCallback);

req.on('error', function(e) {
    throw e;
});

req.end();
};



var d = function(data) {
    console.log(data["INR"]);
    currencies["INR"].amount = data["INR"];

    r = data;   
};


getRates(d);
    console.log(r);

1 Answer 1

1

Why do I always get undefined?

Your problem is not an scope issue but a misunderstanding of async execution. In this code you are printing the value of r before it is assigned.

The execution of your code is as follow:

  1. getRates() is called
  2. console.log(r) is called (hence you get undefined)
  3. When the request executed in getRates finishes your callback is THEN executed. This is when you are assigning a value to r but by then is too late since you already printed it.

In general, you cannot expect the next line to have a value that will be assigned via an async callback. Instead you should reference the value inside the callback. In your case you should move the console.log(r) inside your callback function d.

Sign up to request clarification or add additional context in comments.

1 Comment

Hector, thanks for your reply. I need r to be passed onto module.exports. That's why I am printing console.log(r) out of the async execution. Is it possible to pass 'var r ' to module.exports like module.exports = r?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.