0

I am just trying to make a simple cryptocurrency price ticker and I can't for the life of me figure out how to export a global variable that I set properly.

var btcPrice;

setTimeout(function(){
  axios.get("https://api.cryptonator.com/api/ticker/btc-usd").then((response) => {
    btcPrice = response.data.ticker.price;
    console.log(btcPrice);
});
}, 5000);

setInterval(function(){
  console.log(btcPrice);
}, 10000);

exports.price = btcPrice;

The setInterval shows the price of bitcoin, as it should. But, when I call it in another file, I get undefined as if it's being exported before the setTimeout finds the value. Any ideas how to export the price? Much appreciated!

Setheroni
  • 145
  • 2
  • 12
  • 1
    You can't. Export a Promise instead, or better yet: an object that has a function called getPrice that returns a Promise. – Paul Jan 12 '18 at 22:04
  • seems this btcPrice should be a Promise – Pac0 Jan 12 '18 at 22:04
  • In your current code, you set `exports.price` only *once*, and that's by the time your module is *first imported*, because that's when node.js will construct the module object. Also, `btcPrice` is in fact local to the module object, and not a global. Unless you export the promise itself, `exports.price` will always be `undefined`. – Flávio Lisbôa Jan 12 '18 at 22:08
  • I've been sitting here trying to turn that into a promise and I'm completely lost. – Setheroni Jan 12 '18 at 23:06

0 Answers0