You haven't understood how
async
and
await
work.
The result of an
async
function is a
Promise
, which will be resolved at some later time with the actual return value. Inside another
async
function, you can
await
that
Promise
to get the return value:
async function showPosition(position){
...
data = await fetchData(url);
console.log(data);
}
Outside of an
async
function, you have to sign up to the
Promise
object's success callback:
function showPosition(position){
...
fetchData(url).then(function(result){
data = result;
console.log(result);
});
}
Both versions are equivalent. In both cases, you cannot access the return value until the promise has been resolved.
You also don't want the parentheses on the
window.onload
line - that calls the function and assigns the result to the event, rather than adding the function as a handler for the event.
Change your code to:
async function fetchData(url){
let response = await fetch(url);
let data = await response.json();
return data;
}
async function showLocation(position){
const KEY = "APIKEY";
let lat = position.coords.latitude;
let long = position.coords.longitude;
let url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${long}&key=${KEY}`;
let data = await fetchData(url);
console.log(data);
... USE THE DATA HERE ...
}
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
console.log("Geolocation is not supported by this browser.");
}
}
window.addEventListener("load", getLocation);
async function - JavaScript | MDN[
^]
Using Promises - JavaScript | MDN[
^]
EventTarget.addEventListener() - Web APIs | MDN[
^]