0

I am completely new to node.js and I've struck a problem. I'm making a HTTP request to the fixer.io API and assigning the variable 'rate' to the Euro's exchange rate. That's all working fine. However, I then need to access 'rate' outside of the function. I can't use another function to access 'rate' because the code that uses 'rate' only works correctly outside of a function, so I don't think callbacks are an option. Here's part of the code:

var http = require('http');
var options = {
  host: 'api.fixer.io',
  port: 80,
  path: '/latest?base=GBP',
  method: 'GET'
};
http.request(options, function(res) {
  var data = '';
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    data += chunk;
  });
  res.on('end', function () { //nested function
    const json = JSON.parse(data); //parse JSON response
    var rate = json.rates.EUR; //assign rate for EUR to variable rate
    console.log(rate+"\n")
  });
}).end();

console.log(rate+"\n")
console.log("One pound is currently worth "+rate+" euro"); //this stuff can't be in a function
//do stuff with rate

I've found promises, but I'm not very sure how to use them. Any help would be greatly appreciated. Thanks!

  • 1
    You don't. The timing of when the variable is set is ONLY known inside the callback and thus can only be used inside the callback on in some function you call from there. That's how async development works in Javascript. – jfriend00 Nov 19 '17 at 09:50
  • 1
    Possible duplicate of [How to return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – str Nov 19 '17 at 09:56
  • "I can't use another function to access it because my code only works outside of a function" That makes no sense. – str Nov 19 '17 at 09:56

0 Answers0