0

I use fetch to load json data which works fines. I am trying to return that data back to another function but I am getting undefined. It should be a simple return because the data is there. Am I doing something wrong inside the then?

The console.log(data); displays that data fine. However console.log(gameData); gives me an undefined

(function loadGameData () {
   var gameData = loadData('assets/gameData.json');
   console.log(gameData);
})();

function loadData(json) {
    fetch(json)
        .then(response => response.json())
        .then(data => {
            console.log(data);
            return(data);
        }); 
}
Keith Power
  • 13,891
  • 22
  • 66
  • 135
  • 1
    You are trying to get an asynchronous result in a synchronous way. That is like pressing the Order button on a pizza website and be surprised that your plate is still empty. Moreover `loadData` doesn't return anything. You must wait for the data to be available, so (1) *return* the `fetch.....then()` result, (2) make `loadData` an `async` function, and (3) get the result with `= await loadData(...)`. All info in related dupe reference. – trincot Dec 13 '20 at 13:08
  • ah ok makes sense, thanks – Keith Power Dec 13 '20 at 13:11

0 Answers0