0

How to fetch data then save inside a variable?

var store;

fetch('https://api.coindesk.com/v1/bpi/historical/close.json?start=2013-09-01&end=2013-09-05')
.then(function(response) {
  return response.json();
})
.then(function(data) {
  store = data;
  console.log('Data is', store);

})
.catch(function(err) {
  console.log('Unable to fetch the data', err);
});

console.log(store);

console.log gives me undefined variable. Can someone describe how does it work?

  • But here I used to fetch API not ajax, could you please explain how does it work? – Baha Sultanov Nov 26 '18 at 20:27
  • https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron – Evert Nov 26 '18 at 20:27
  • 1
    @BahaSultanov doesn't matter what you *call* it. The same principles apply. You can use Promises or callbacks or things more exotic, but asynchronous control flow is what it is. – Jared Smith Nov 26 '18 at 20:58

1 Answers1

0

I'm assuming the undefined console log you're talking about is the last one. I reproduced your fetch code, and it worked perfectly. What I think is happening is that the last line (console.log(store)) occurs before the store variable has been updated as part of the fetch line, because fetch is asynchronous.

If you need to do something with the result of fetch, it either has to be nested in the promise resolution (ie, where you redefine store), or use async/await, to make the fetch code work synchronously, and run before your console log at the end.

Sasha
  • 6,224
  • 10
  • 55
  • 102