[Solved] Weather App -- Issue with async

[Solved] Weather App -- Issue with async
0.0 0

#1

Hi all,

I’m building my weather app, and I’ve hit a wall when trying to get the user’s location. My issue isn’t with getting the location, but with getting JS to wait while the data is pulled. I understand that I need to use a callback function, but I can’t find a tutorial that explains this in a way that helps.

This function gets, and returns, the user’s coordinates:

function getLocation() {
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        var userCoords = [position.coords.longitude, position.coords.latitude];
        return userCoords;
    });
} else {
    console.log("Geolocation not supported!");
}
}

The above seems to work. If I print userCoords, it works fine and doesn’t return undefined.

This function is going to call the weather API after it pulls the coordinates from the above (I haven’t added the API functionality yet). The coordinates aren’t being assigned to the variable (at least not before I check it with console.log):

function getWeather() {
var userCoords = getLocation();
console.log(userCoords);
}

Any idea how I can get this to work?

Thanks guys!


#2

Yes. You need to use a callback for that. In this case you cannot use a variable to store the value, you can’t assign the value to the variable outside of the callback function either. You need to do all that stuff inside the callback function with the value it passes as an argument, that is your variable.

JQuery’s json method looks like this:

//do things here with yourjsonresponse
});```

If you're using something else to get the json file (like angular) it's better to check their docs and see if it uses a callback function or promises (that are almost the same thing).

#3

Shin8 is right.

Since you have to make at least 2 API calls here you will have a bunch of things nested something like:

navigator.geolocation.getCurrentPosition(function(position) {
     var userCoords = [position.coords.longitude, position.coords.latitude];
     $.getJSON('url', function(data) {
             //now you have your data
             //post data to DOM or call a function or something
      });
 })

That is the most straight forward way. If you want you can also look into javascript promises which do the same thing but offer nicer syntax.


#4

Thanks @Shin8! I got it working.


#5

Thanks @RadDog25!

I didn’t use promises, but they definetly look much nicer.