0

How do i get the value of variable 'price' and pass it as a global variable so I can use it elsewhere in my program?

gdax.loadMidMarketPrice(product).then((price: BigJS) => {
    console.log('Mid-market Price: $${price}/BTC');
}).catch(logError);

I tried this but the variable is not visible outside the function

gdax.loadMidMarketPrice(product).then((price: BigJS) => {
    var midprice=price;
    console.log('Mid-market Price: $${price}/BTC');
}).catch(logError);
Jin
  • 69
  • 2
  • 3
  • 11
  • In a browser: `window['midprice'] = price;`. In Node.js: `global['midprice'] = price;`. Then you have to `declare var midprice: any` somewhere in a file TS definition file. But it is a **very bad practice**. – Paleo Sep 27 '17 at 08:29
  • how is this used? do you want to make this available? in what environment, what other technologies. – toskv Sep 27 '17 at 10:46
  • Just want to make the variable available to other functions in the same typescript file. – Jin Sep 27 '17 at 10:59
  • that's a bit vague too, how are those functions called? you could just move the `var midprice` outside the **then** function. But the variable will be initialized asynchronously and it might be null if used before the callback finishes. – toskv Sep 27 '17 at 11:09

1 Answers1

1

Well, you say you have everything in the same typescript file. Then simply move the variable out of the function

var midprice;

gdax.loadMidMarketPrice(product).then((price: BigJS) => {
    midprice = price;
    console.log('Mid-market Price: $${price}/BTC');
    someOtherFunc();
}).catch(logError);

function someOtherFunc() {
    console.log("Hey, I can see it! It's " + midprice);
}
kayahr
  • 20,913
  • 29
  • 99
  • 147
  • I tried this, but the console log would say midprice is undefined – Jin Oct 04 '17 at 06:23
  • @Jin Then something is wrong with your code. In my example `midprice` is set BEFORE `someOtherFunc` is called and therefor the variable must exist. Maybe you tried some other code and are accessing `midprice` before it is set? Maybe you can get replace the unknown `gdax.loadMidMarketPrice` call in your example with a dummy so we can reproduce your exact problem? – kayahr Oct 07 '17 at 09:32