Help with what must be a stupid mistake but I can't find it

Help with what must be a stupid mistake but I can't find it
0.0 0

#1

Hi there,

I’ve knocked together a first draft on the Weather project, to get the api part working. I had it working earlier, when I had function getWeather() set to retrieve data on a button click.

Now I have gotten rid of the button click, because I want the data retrieved on document.ready. But the function getWeather() is not working anymore. It’s as if the global variables aren’t global anymore.

I would appreciate a fresh set of eyes looking at this, to see what I’ve done wrong.

Thank you!

My code:


#2

You should call getWeather from inside the geolocation callback, and immediately pass it the URL that you’ve constructed there.

Yeah, it’s as if the global variables aren’t global anymore. It’s because both getting the location and requesting for weather data are asynchronous, and they tend to be needed to “chain” together in order to work properly.


#3

Hey. The .getCurrentPosition method is asynchronous. You’ll need to call your getWeather() function inside the method’s success callback like so:

navigator.geolocation.getCurrentPosition(function(position) {
  lat = position.coords.latitude;
  long = position.coords.longitude;
  url = "https://fcc-weather-api.glitch.me/api/current?lat="+lat+"&lon="+long;
  getWeather(url);
});

Then, you’ll only need to reference your getLoc function in the .ready jQuery method:

$(document).ready(getLoc);

#4

Thank you, kevomedia and noyb - your corrections make it work.

But, for my education, is there no way to store the result of asynchronous calls like getCurrentPosition or the call to retrieve the JSON data in a variable, such that they can be used later?


#5

You can store the JSON data inside your getJSON callback function. The catch is, you can really only use it within code that is inside this callback function. This code could include multiple function calls using the data, so would be how you would do something else with the data once it is returned.

Another point to make is let’s say you had a getJSON call to an API which will get back a huge JSON (an array with over 10 million objects in it). This is going to take some amount of time to get all this data back from the API. How long will depend on the user’s internet connection. Since you do not know how long it will take, it would be tough to “know” when it is safe to use this data. Ultimately, you have to change your thinking a little when dealing with asynchronous functions.


#6

Thanks, that makes sense. I appreciate your taking time to explain it this way.