0
var Data;
fetch('url')
    .then(data => data.json())
    .then(success => Data = success);


while(typeof Data === 'undefined'){
  console.log("data not retrived")
}

The code above gets me into a forever loop and I don't understand why, Can someone expalain this?

  • 2
    `let response = await fetch('url');` https://stackoverflow.com/questions/54950838/how-to-use-fetch-with-async-await – GrafiCode Sep 04 '22 at 19:41
  • Does this answer your question? [How to access the value of a promise?](https://stackoverflow.com/questions/29516390/how-to-access-the-value-of-a-promise) – evolutionxbox Sep 04 '22 at 19:43
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Robin Zigmond Sep 04 '22 at 19:55

1 Answers1

1

It happens because of javascript's asynchronous, non-blocking behavior. As it doesn't know how much time it will take to get the response from the server, it won't wait for it, rather it will execute the next while loop portion of the program. That's why your 'Data' variable's value will remain 'undefined' and results in an infinite loop.

  • At some point the server response should arrive and Data should be assigned to the response, thus not being undefined and therefore breaking the loop? What am I not understanding, wrapping the fetch in an async function does not help either – Emil Johansson Huzell Sep 05 '22 at 17:03