'How to wait an async function before returning a value in a function?
In my code below, I want to get the country location of a user, using google geocode API.
The country variable is set after the axios function is called.
However, getCountry() returns an empty object. How do return the value only after country has been updated?
Trying to get a hang of asynchronous functions in Javascript. Any help is appreciated,thanks.
import axios from "axios";
const getCountry = () => {
const pos = {};
let country = {};
// get the geolocation lat&lng
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(findLocal, showError);
} else {
console.log("Geolocation is not supported by this browser");
}
async function findLocal(position) {
pos.lat = position.coords.latitude;
pos.lng = position.coords.longitude;
// using google maps API to get the address with lat&lng
await axios(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${pos.lat},${pos.lng}&key=${process.env.REACT_APP_GOOGLE_API_KEY}
`).then((response) => {
if (response.data.status === "OK") {
// get the address
let address_components = response.data.results[0].address_components;
for (var i = 0; i < address_components.length; i++) {
if (address_components[i].types[0] === "country") {
// get the country
country = {
long_name: address_components[i].long_name,
short_name: address_components[i].short_name,
};
break;
}
}
}
});
}
function showError(Error) {
console.log(Error);
}
// return country object with long_name and short_name
return country;
};
console.log(getCountry()); // actual_result = {}; intended_result = {long_name: value, short_name: value}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
