New JS programmer here, and still trying to understand async
and await
. The following simple example is intended to retrieve the user's location and then update a global variable. I realize that I have to click on the "allow location access" pop-up, but why doesn't the program pause until that happens?
Instead, the callback is skipped (apparently) forever. That is, there is never any output string "In setUserLocation", and the final printed value of userLocation
is the same as the original value. No uncaught error shows up in the console (I did have error checks in the original code).
EDIT: I added an error handler callback to getCurrentPosition
. Basically, it gets invoked if I click "block access" when prompted to allow access to location. Otherwise the program behaves as before.
var userLocation = {lat: "40.0", lon: "-90.0", name: "Default Location"}
function setUserLocation(position) { // callback function
console.log("In setUserLocation") // never executed -- why?
lat = position.coords.latitude.toString();
lon = position.coords.longitude.toString();
userLocation.lat = lat ;
userLocation.lon = lon ;
userLocation.name = "New Location" ;
console.log(userLocation) ;
}
function failedLocation() {
console.log("Something went wrong")
}
async function retrieveLocation() {
console.log(userLocation) ;
console.log("Getting location") ;
await navigator.geolocation.getCurrentPosition(setUserLocation,failedLocation);
console.log("Got location") ;
console.log(userLocation) ;
}
retrieveLocation() ;