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!