0

I have the following code

binance.prices('BNBBTC', (error, ticker) => {
    priceNow = ticker.BNBBTC;
    console.log(priceNow)
  });

But I need to use the variable "priceNow" outside of that function, I have tried many things, for example:

 var priceNow = ""

  binance.prices('BNBBTC', (error, ticker) => {
    priceNow = ticker.BNBBTC;
    // console.log(priceNow)
  });

  console.log(priceNow) //But this just say nothing

But this doesn't work, I can't update the global variable from the function, why does this happen? and because if it works in example like this:

var a = 10;

myFunction();

function myFunction(){
   a = 20;
}

console.log("Value of 'a' outside the function " + a); //outputs 20
Jabibi
  • 35
  • 2
  • 7
  • Your last example is different, as your function is being called before your `console.log` runs. In your 2nd example, you're doing `console.log()` before the callback function is executed – Nick Parsons Apr 01 '21 at 23:48
  • but how can I adapt this to my code? I am trying to investigate about asynchronous functions, but the truth is that everything I have tried so far has not worked for me, and this in theory should be simple, can you help me? – Jabibi Apr 02 '21 at 02:01
  • You’ll need to use priceNow (ie: ticker.BN BTC) inside of your callback function, you won’t be able to use it outside of it. The other option is to use a Promise, which wraps this call (using Promises is shown on the second link above). You can then either use .then or await the Promise to get the priceNow value – Nick Parsons Apr 02 '21 at 02:09
  • that's what i'm trying but nothing works using it inside the function is not an option actually, I just needed it to display it in a specific console.log – Jabibi Apr 02 '21 at 02:46
  • Can you edit you question to show your new attempt – Nick Parsons Apr 02 '21 at 04:10

0 Answers0