About to rip my head off with these asynchronous function. Weather API

For the life of me I cannot figure out what I am doing wrong. I’ve tried many different variations of this, right now this is currently what I have.
I cannot seem to pass in the longitude and latitude variables into the ajax function if I obtain them from the myPosition function. However, if I explicitly assign the variable a number in the code, such as what I have commented out, the code runs fine and clearly console.log’s the response.timezone.

These asynchronous functions are really giving me a headache. What am I doing wrong here?

var latLong = document.getElementById("latLong");

var lat = document.querySelector("#lat");
var long = document.querySelector("#long")

function myPosition (position){
  	 lat.textContent  =  position.coords.latitude;
 		 long.textContent  = position.coords.longitude;
 		 
 		 lat = Number(lat.innerHTML)
 		 long = Number(long.innerHTML)
 		  console.log(lat);
 		  console.log(long);
	}

	 // 	lat = 33
 	// long = -123.4443
	 		  
console.log(lat, long)
 		  
function getWeather(){
	
	$.ajax({
		url: "https://api.darksky.net/forecast/96dd30a49debe62a67b208f705e3d706/" + lat + "," + long,
		dataType: "json",
		success: function(response){
		console.log(response.timezone)
		}
	})
}

if (navigator.geolocation){
  navigator.geolocation.getCurrentPosition(getWeather)
  console.log(long);
}
else {
  latLong.innerHTML = "sorry, position not avaliable"
}

window.addEventListener("load", function(){
	getWeather();
})

Yes, it’s a confusing way to think. Frustration is normal.

Asynchronous functions take a different way of thinking. JS is different than a lot of programming languages in that it is inherently asynchronous. In many programming languages, the code will wait until something is done before moving onto the next thing. In those languages doing anything asynchronously is a pain. Because JS is for the web, where so much is asynchronous, it doesn’t wait. Say that to yourself, “JS never waits.” (OK, there are some ways to make it wait, but that isn’t the issue here.)

So, in your code, what’s happening is navigator is getting called and while is in async land, JS continues on and tries to make the weather call without lat and lon being defined yet.

There are different ways to handle this. A callback function is the easiest (for now). So, you might have something like:

navigator.geolocation.getCurrentPosition(function(data) {
  // make your weather api call in here
  // this won't run until the location comes back
});

Also be aware that geolocation has been having some lag issues, especially on multiple calls. It may be good to hardcode the lat and lon for development.

Here is a pen I wrote a while back to help explain async. Maybe it will help.

Yes, it is very confusing. Once you wrap your head around it, it is a very powerful tool for web dev.

Awesome man. Well, it looks like when I use a callback function exactly like the one you posted, everything works great. Which is good, because I was starting to think a lot of my other code was messed up.

So essentially, since they are asynchronous, you to put them within each other (callback function) in order for it to use the data from the api call?

That’s the only snippet I was missing. Now I am able to get the data on my page, so now I just have play with iti and manipulate it to change depending on the weather conditions, temp, etc.

Also, any resources you’d recommend to learn more about asynchronous functions? I still really am not getting the concept to well, it’s difficult to wrap my head around. But it is getting clear

Thanks again!

So essentially, since they are asynchronous, you to put them within each other (callback function) in order for it to use the data from the api call?

Yeah. That’s the “callback” - the asynchronous function (AJAX calls, etc.) “comes back and calls” that function. Anything that needs the data from that AJAX call must either be in that callback function or called from it.

There are other ways to handle asynchronous data, but callbacks are the most basic and a good introduction.

Also, any resources you’d recommend to learn more about asynchronous functions?

I think you just need to understand the concept (which you’re starting to) and use them a lot. You’ll run into some of the pitfalls as you go. Make sure you understand that pen I gave. I might check out a few youtube videos, but other than that you just gotta use them. Later on you can learn about promises and async/await, but for now callbacks will work fine.

Got it. You really cleared it up for me. Now I am starting to understand it a lot better. These API calls are actually pretty fun to use, especially when you’re always displaying different data on the screen based on your location, the day of the week, the time of day, etc.

Like you said, I just need to use API’s and callbacks more in order to understand them. For a side project, after I finish this, I want to create my own page that grabs data from another server. Only problem there is that I have to see if those API’s exist (for whatever topic I choose), so I am limited to what json data I can find on the internet.

Thanks for the help man, I am really starting to understand it. Now I just need to style the page based on the weather, temperature, time of day, location, etc and have the page have a responsive style based on these factors.

One more quick question - is codepen going to act funky with these API calls? I am coding this all in sublime and I am worried codepen is going to give me a CORS error or something similar

Yeah, API’s aren’t just laying around - they have to be specifically set up. And then they have to be not requiring authentication and documented well.

If you want to practice, there are sites like JSONPlaceholder that have “fake” data to which you can make AJAX calls. But really, I didn’t fully understand AJAX until I did the backend section and started building my own APIs. But you can mess around and get a basic understanding of it from the frontend for now.

If you want to get a little deeper, you may want to try using Postman, a tool that allows you to control how http requests are made and manually change the variables and see exactly what you get back. I’m sure there is a youtube video about it.

yeah, i’ve tried to use postman before, and in the videos that i did watch of it, I really did not understand it at all, so I decided to ignore it right now until I start understanding this stuff better

Yeah, maybe it’s too much right now. It’s just nice because you can really see what is happening. But if it isn’t resonating for you, I’m sure you’ll find a way that does.