Async Functions

How do I get the getLocation function to return the newURL variable?

var url = "https://fcc-weather-api.glitch.me/api/current?";
var urlTest = "https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139";

var getLocation = async() => {
  var newURL;
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      let lon = position.coords.longitude;
      let lat = position.coords.latitude;
      newURL = url + 'lat=' + lat + '&lon=' + lon;
      document.getElementById('location').innerHTML = "latitude: " + lat + "<br>longitude: " + lon;
      document.getElementById('URL').innerHTML = newURL
    });
  }

  return Promise.resolve(newURL);
}

// newURL is undefined but urlTest works
var getWeather = async(URL) => {
  fetch(URL)
    .then(res => res.json())
    .then(data => JSON.stringify(data))
    .catch(err => console.log(err))
}
    
async function App() {
  const location = await getLocation();
  const weather = await getWeather(location);

  document.getElementById('URL').innerHTML = location
  document.getElementById('weather').innerHTML = weather
}

App()

Couple problems:

  1. Function coupling
    You don’t want getLocation to depend on url, it’s bad! getLocation should only get location and then getWeather should take location and get weather!

  2. You await for getLocation expecting a promise from it and that’s correct, however you have to resolve this promise inside a callback function that you’re passing to navigator.geolocation.getCurrentPosition. You won’t be able to do this with async and instead have to return new Promise:

const getLocation = () => new Promise((res) => {
  window?.navigator?.geolocation.getCurrentPosition((position) => {
    const { coords } = position;
    res(coords);
  });
});
1 Like