2

In my javascript code, I use the fetch() command to receive some data from my php file:

fetch('php/get_comm.php').then(response => response.text()).then(data => {
       communities = JSON.parse(data);
});

Now there is some more code to be executed that uses the data acquired using fetch.

Since fetch is an asynchronous function, the rest of the script starts executing before the fetch command finishes, hence they cannot use the variable "communities".

Currently I'm using this trick as a work around:

fetch('php/get_comm.php').then(response => response.text()).then(data => {
       console.log(JSON.parse(data));
       communities = JSON.parse(data);
       continueScript();
});

function continueScript() {
       // Rest of the script.
}

This seems like a very messy way of doing this. Is there any other more clean way to accomplish what I want?

cherryguy
  • 135
  • 7
  • 4
    The (general) approach you're currently using is perfectly fine, though I'd suggest passing the `communities` as an argument instead of using a global variable. You can also use `.json()` instead of `.text()` followed by `JSON.parse`. – CertainPerformance Oct 25 '21 at 02:16
  • 3
    https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await – Phil Oct 25 '21 at 02:17
  • There is absolutely nothing messy about this. It is the idiomatic way of doing things IMO – sinanspd Oct 25 '21 at 02:17
  • 1
    A less messy way is to pass `communities` as the argument to `continueScript`, instead of defining it as a global function. You can also look into async/await – Evert Oct 25 '21 at 02:19

0 Answers0