-1

I'm trying to retrieve data (currency rates) from open API with Fetch. Everything works fine and JSON object is successfully logged to console. However, I need that data to be accessible to all other functions as well. getCurrencyRates function should return the JSON object, but it returns "undefined". What is the problem?

<script>
  fetch('https://api.exchangeratesapi.io/latest')
      .then(function(response){
        return response.json();
      }).then(function(json){
    getCurrencyRates(json);
  }).catch(function(error){
    console.log(error);
  });
  // This function should return currency rates in JSON object
  function getCurrencyRates(rates) {
    console.log(rates);
    return rates;
  }
</script>
Mr. Engineer
  • 215
  • 1
  • 9
  • 26
  • make use of promises! Wrap fetch into a promise resolving to the data you need. – Mohammad Basit Sep 23 '20 at 10:48
  • ....or you can store you response in a `global variable` to be accessible to pass onto other functions as required. – Always Helping Sep 23 '20 at 10:55
  • you need to look into `async` and `await` – Kharel Sep 23 '20 at 11:05
  • The problem was solved thanks to @Always Helping, but his answer disappeared for some reason... – Mr. Engineer Sep 23 '20 at 11:52
  • @Mr.Engineer that’s because the answer was very low quality and error prone. This question is a duplicate, look at the answer to the other question to find out how to PROPERLY do asynchronous programming. – Adam Jenkins Sep 23 '20 at 14:21
  • @Mr.Engineer Glad to hear that it worked for you. I was happy to help. I deleted my answer since the duplicate question provides **other ways** of solving this issue as well. But i **completely disagree** with @ Adam where he thinks that my answer was error prone or low quality because it was not at all since it was addressing this question directly and provided a working solution which did solved the issue. – Always Helping Sep 23 '20 at 20:53

1 Answers1

-2

You could do something like this:

<script>
let currencyRates;

  fetch('https://api.exchangeratesapi.io/latest')
      .then(response => response.js()
      .then(function(json){
         currencyRates = json;
      }).catch(function(error){
      console.log(error);
  });

  // This function should return currency rates in JSON object
  function getCurrencyRates() {
    return currencyRates;
  }

function anotherFunction() {
   console.log(getCurrencyRates());

   // or just:
   console.log(currencyRates);
}

</script>
micke
  • 117
  • 1
  • 6