0

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
ZK Zhao
  • 19,885
  • 47
  • 132
  • 206
  • 2
    Your console.log is happening before the function returns. That's the asynchronous nature of how api calls are handled. So, you need to put any code that relies on the returned data inside the function where you currently have `price=data.bpi` – Lee Taylor Oct 06 '19 at 02:31
  • Consume the data in the callback – charlietfl Oct 06 '19 at 02:36

2 Answers2

0

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);
});
0

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.

Rocky Sims
  • 3,523
  • 1
  • 14
  • 19