I need to assign values from a json api. But due to fetch being async, it is finished after some of the js is executed. So how do I tell the code to wait for the fetch to finish and "load" the data before moving on in the code?
I've tried adding the code in the ".then" and "=>" option, which kind of works, but breaks most of the later code. And after trying possibly dozens of advice from various stackoverflow and other websites I am still completely lost.
var latitude = 0;
var longitude = 0;
var city = "";
fetch("http://ip-api.com/json/?fields=lat,lon,city").then(function (response) {
return response.json();
}).then(function (response) {
latitude = response.lat;
longitude = response.lon;
city = response.city;
});
var center = SMap.Coords.fromWGS84(latitude, longitude);
...
I need to first execute everything (assign json data to my global variables) in this function before moving on to other code.