1

I am making a fetch request that returns the usual promise. How can I get the result to be saved to a variable that I can use outside the fetch function?

This doesn't work:

let test

fetch("[request URI]", requestOptions)
  .then(response => response.text())
  .then(result => { test = result } )
  .catch(error => console.log('error', error));


console.log(test); // undefined

Edit:

let test

fetch("[request URI]", requestOptions)
  .then(response => response.text())
  .then(result => { console.log(result) } ) // here
  .catch(error => console.log('error', error));

works and prints the result to the console. So I am aware of how to process the result of an asynchronous request, but having trouble updating a global variable.

Lone Wallaby
  • 159
  • 1
  • 1
  • 9
  • 1
    You have no trouble updating a global variable, that works just fine. You have trouble with timing - you're logging the global variable before it has been updated. That's why you have to call the code that needs the value from inside the `then` callback; there's no way around this. – Bergi Nov 20 '22 at 17:12

1 Answers1

0

What happen if you try :

let test

fetch("[request URI]", requestOptions)
  .then(response => response.text())
  .then(result => { console.log(result) } ) // here
  .catch(error => console.log('error', error));

Wawa
  • 273
  • 2
  • 11