Weather app - Question about organizing code

Weather app - Question about organizing code
0

#1

So I was working on the weather app, and I got to the point where I have two functions, both using a different API:

getUserLocation() // Gets coords from freegeoip.net
getLocalWeather() // Uses the coords to get weather info

To make sure I have the right coordinates before going further, I call the getLocalWeather function inside the ajax callback of getUserLocation:

function getUserLocation() {
    $.getJSON("https://freegeoip.net/json/", function (data) {
        getLocalWeather(data.longitude, data.latitude);
    });
  }

That works, but it doesn’t seem very proper. I might want to use the coordinates for different things in the future. What would be the best way to separate the functionality while making sure the functions get called in the right order?


#2

I would write like u did.
For further use of coords u need to save it in global var, just make aware of this:

var myData = null;
function getUserLocation() {
    $.getJSON("https://freegeoip.net/json/", function (data) {
        myData = data;
    });
  }
getUserLocation();
console.log('myData: ' + myData); // myData: null

Or to escape this async mode u can nest this $.getJSON in getUserLocation with other function
like updateMyCoordsOnScreen, etc…

U can also specify

$.ajaxSetup({
    async: false
});

and then use getJSON in sync fashion