0

I'm trying to get a value from a fetch function, but it arrives later then I try to use it. How can I make all my further program wait until this value arrives?

    let res = 'Invalid query';

    function callback(result) {
      res = result;
      console.log('inside callback: ', res);
      return res;
    }

    function getData(callback) {
      return fetch('https://api.sunrise-sunset.org/json?lat=36.7201600&lng=-4.4203400')  
      .then(response => response.json())
      .then(json => {
        callback(json.results.sunrise);
      })
      .catch((error) => {
        console.error(error);
      });             
    }

    getData(callback); // returns to console: inside callback:  5:46:40 AM -> which is what I need
    console.log(res); // returns 'Invalid query', which is an initial value

If I use

    setTimeout(function() { console.log(res); }, 2000);

it gives the right result, but I need all my further program to wait for this value either.

  • Get rid of `callback` entirely. Just: `function getData() { return fetch("url").then(response => response.json().results.sunrise); }` Note that I also removed your `catch`; using `catch` where and how you did in `getData` converts the rejection into a resolution with the value `undefined`. Leave it to the caller of `getData` to worry about errors. Then: `getData().then(res => console.log(res)).catch(err => console.error(err));` – T.J. Crowder Apr 12 '17 at 09:47
  • @T.J.Crowder, thanks, that works but only with second "then" - like this: function getData() { return fetch("api.sunrise-sunset.org/…) .then(response => response.json()) .then(json => json.results.sunrise); }. But it still doesn't tell me how to use this value, how to update my initial res variable with the value from response – Kateryna Hurenko Apr 12 '17 at 10:14
  • No, you don't need two `then`s, look closely at my example above. Yes, it does tell you how to use `res`: *Within* the `then` callback. See the linked question's answers for details. – T.J. Crowder Apr 12 '17 at 10:16
  • @T.J.Crowder, thank you – Kateryna Hurenko Apr 12 '17 at 10:35

0 Answers0