I've been trying to get web javascript to fetch some dynamic data from a URL and store it in a variable. However, for some reason anything that I return from the then() functions becomes an object promise, even if I wrote "return x;" where x is a string/array/etc..
Here's the code that I currently have.
The response from "api/fullGameData" is {"fullGameData":[0,0,0,0,0,0,0,0,0]}
let fullGameData = fetch("api/fullGameData")
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
}
)
fullGameData = fullGameData.then((json) => {
let fullGameData = json.fullGameData;
console.log("test= " + fullGameData);
return fullGameData;
})
console.log("fullGameData= " + fullGameData);
I expected both of the console.logs in there to print the exact same thing, but no matter what I do the console says
fullGameData= [object Promise]
test= 0,0,0,0,0,0,0,0,0
and I have no idea why. I've tried putting other console.logs in other places but it's always the same result, 0,0,0,0,0,0,0,0,0
if the console.log is in one of the .then() functions and [object Promise]
otherwise. I really need to use the contents of the fullGameData
variable elsewhere so I can't just do everything in the .then functions.
Thanks in advance for any help :)