Can someone explain to me why my async function is not awaiting for my getLocation function to finish?
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 newURL = url + 'lat=' + lat + '&lon=' + lon;
var lon;
var lat;
var name;
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
lon = parseFloat(position.coords.longitude);
lat = parseFloat(position.coords.latitude);
document.getElementById('location').innerHTML = "latitude: " + lat + "<br>longitude: " + lon;
});
}
}
function getWeather() {
return fetch(newURL)
.then(res => res.json())
.then(data =>
name = data.name
)
}
// await is not working
async function App() {
await getLocation();
await getWeather();
document.getElementById('weather').innerHTML = name
}
App()
Thank you for the feedback. So this is what I’ve come up with, but its still not working:
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 newURL = url + 'lat=' + lat + '&lon=' + lon;
var lon;
var lat;
var name;
var getLocation = new Promise((resolve) => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
lon = parseFloat(position.coords.longitude);
lat = parseFloat(position.coords.latitude);
document.getElementById('location').innerHTML = "latitude: " + lat + "<br>longitude: " + lon;
});
}
resolve();
})
var getWeather = new Promise((resolve) => {
fetch(newURL)
.then(res => res.json())
.then(data =>
name = data.name
)
resolve();
})
// await is not working
async function App() {
await getLocation;
await getWeather;
document.getElementById('weather').innerHTML = name
}
App()
Try assigning the await functions to variables (respectively) and then call the property.
async function App() {
const location = await getLocation;
const weather = await getWeather;
newURL is only defined within the getLocation function.
urlTest works because it’s been declared globally.
You want the getLocation function to return the lat and long data.
var newURL;
var getLocation = new Promise((resolve) => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
let lon = position.coords.longitude;
let lat = position.coords.latitude;
document.getElementById(‘location’).innerHTML = "latitude: " + lat + " longitude: " + lon;
});
}
resolve();
return { lat, long };
})
newURL = url + ‘lat=’ + getLocation.lat + ‘&lon=’ + getLocation.lon;