Q: javascript & api calls: how to get value returned from an api call? For example, if I define code like this
var price;
$.getJSON('https://api.coindesk.com/v1/bpi/historical/close.json?start=2013-09-01&end=2013-09-05', function( data ) {
  price = data.bpi;
});

then I can get price from console;
However, if I define code like this
var price;
$.getJSON('https://api.coindesk.com/v1/bpi/historical/close.json?start=2013-09-01&end=2013-09-05', function( data ) {
  price = data.bpi;
});
console.log(price);

the price can still be accessed from console, but console.log returns undefine.

My question is that how can I get the price returned from data.api, so I can latter use the data to do some further calculation, such as
var x = Object.keys(price);
var y = Object.values(price);
// some plot using x, y, and some calculations


A: The get method is asynchronous meaning that the code execution proceeds to the statement after the get block without waiting for it. Once the get call completes, the code inside the get block is executed with the result returned. Thus, the console log statement is executed even before the call has finished and is undefined.
If you want to process the data returned, all calculations have to be done inside the callback method of the get() function.
  $.getJSON('https://api.coindesk.com/v1/bpi/historical/close.json?start=2013-09-01&end=2013-09-05', function( data ) {
  price = data.bpi;
  var x = Object.keys(price);
  var y = Object.values(price);
});


A: I think javascript promises are what you're looking for.


const promise = new Promise((resolve, reject) => {
  const url = 'https://api.coindesk.com/v1/bpi/historical/close.json?start=2013-09-01&end=2013-09-05';
  $.getJSON(url, data => {
    resolve(data);
  });
});

//and then later

promise.then(data => {
  console.log(data.bpi);
});
<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
  </head>
  <body>
    
  </body>
</html>


price = data.bpi; can't run right away but your code continues to execute so console.log(price); runs before price = data.bpi;.
Also when you want to use the data later you might have to wait for it to be available. That's what the promise is doing.
