[Weather App] how to wait for geolocation to finish?

I’m finishing the weather app and i’m finding the weather api is often executing before i can retrieve the latitude and longitiude? Is there a way to wait for geolocation to be succesful before executing the rest of the script? I found some material online but i couldn’t figure out how to apply it to my project. Would really appreciate some help! :smiley:

Thanks in advance!

The reason that the functions are not executing in the order that you expect is because they are asynchronous; that is, instead of running line by line, and in the order that you have coded them, they both start as soon as they can and finish as soon as they can.

There are a few ways that you can handle this type of behaviour. With minimal changes to your code in mind, you can simply rely on the callback function that you give to navigator.geolocation.getCurrentPosition(callback). By simply moving the code for the API call to inside the callback function, it will only be executed once the positions become available—this is because the callback function is only called once navigator.geolocation.getCurrentPosition() has finished what it’s meant to do.

In case the mental model isn’t clear, you can consider navigator.geolocation.getCurrentPosition(callback) as a function that looks like this:

function getCurrentPosition(callback) {
  const position = {
    long: null,
    lat: null

  // Do things that get the geolocation of the user and
  // change position.long and position.lat accordingly

  // ...

  // Return the callback function and pass position in
  // as an argument
  return callback(position);

I hope that helps. :smile:

1 Like

Thankyou so much! Really appreciate the effort of your answer :smiley: