0

Everything works, but how do I bring the variable "data" out of the .then() method so that I can call it later in the program?

fetch("http://localhost:8088/get/value")
.then(response => response.json())
.then(data => console.log(data));
CrimsonTide0
  • 37
  • 1
  • 6
  • So you don't have to read the link, the short answer is replace `console.log` with `globalThis.data=` then you access it anywhere as `globalThis.data`. But it will be `undefined` until the fetch is actually complete. If this trips you up, you will have to read the link =) – GirkovArpa Jul 29 '20 at 19:05
  • Once you are in “promise land”, there is no way out – any code that relies on the data from the response will have to be in the then or subsequently chained then methods. You can only make the code look as if it weren't asynchronous by using async/await – Patrick Hund Jul 29 '20 at 19:06
  • Don't use global variables. Either change to async/await or create an aux variable, declared before fetch, and assign data to it. – nip Jul 29 '20 at 19:06
  • Figured it out, thanks for the help. – CrimsonTide0 Jul 29 '20 at 20:53

0 Answers0