1

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.

petra08
  • 11
  • 1
  • 1
    Your only real choices are to `await` the `fetch` or to call `.then` on it and put all the rest of the code in that – CertainPerformance Dec 30 '18 at 08:01
  • I was a bit worried, I'll have to use it that way, but I thought there would be abit more elegant wait, than .then inception add infinitum...And how do I await the fetch? – petra08 Dec 30 '18 at 08:05

0 Answers0