0

I am trying to set btcPrice in getJSON method. when I write log outside the value of btcPrice still 63000. How catch outside getJSON

var btcPrice = 63000
sovBuyPrice = 0.0001
sovBought = 1027
$.getJSON("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd", function(data){
 btcPrice = data["bitcoin"]["usd"];
}).fail(function( dat, textStatus, error ) {
    var err = textStatus + ", " + error;
    alert(err);
});
console.log(btcPrice);
James123
  • 11,184
  • 66
  • 189
  • 343

2 Answers2

0

What is happening here James is you are making an asynchronous request so the value has not been returned yet from the AJAX request.

Async Await in a promise will force this asynchronous request to wait to be resolved before logging the value.

However I recommend you look into the Fetch implementation as it can be awaited directly since it already returns a promise.

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

(async function(){
    // Variables
    let btcPrice = 63000
    const sovBuyPrice = 0.0001
    const sovBought = 1027
    // AJAX Request
    await new Promise((resolve, reject) => {
      $.getJSON("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd", function(data){
            btcPrice = data["bitcoin"]["usd"];
            resolve();
        }).fail(function( dat, textStatus, error ) {
            var err = textStatus + ", " + error;
            alert(err);
            reject();
        });
    });
 
    console.log(btcPrice);
})();
Michael Paccione
  • 2,467
  • 6
  • 39
  • 74
0

Convert your fetch into a promise, then call it and log the result inside an async function:

function getPricePromise() {
  return new Promise((resolve, reject) => {
    $.getJSON("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd", function(data){
      resolve(data["bitcoin"]["usd"]);
    }).fail(function(_, textStatus, error ) {
      reject(error);
    });
  }
}

async function btcPriceLogger() {
  var btcPrice = 63000;

  try {
    btcPrice = await getPricePromise();
  } catch (err) {
    alert(err);
  }

  console.log(btcPrice);
}

btcPriceLogger()
cd3k
  • 719
  • 5
  • 8