I am subscribing to Google Maps API to pull in coordinates based on an address. My understanding is that by awaiting the subscribe line, it should wait for that code block to finish before moving onto the following lines.
async getCoordinates(address) {
let url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + encodeURIComponent(address) + '&key=' + environment.geocodeKey;
let lat;
let lng;
let coord: Coordinate;
await this.http.get(url).subscribe(data => {
let map = data.json() as Results;
lat = map.results[0].geometry.location.lat;
lng = map.results[0].geometry.location.lng;
console.log("inner lat is: " + lat)
});
console.log("outer lat is: " + lat)
coord = new Coordinate(lat, lng);
console.log("coord lat is: "+ coord.latitude)
return coord;
}
However when I run the app, I see this in the console:
outer lat is: undefined
coord lat is: undefined
inner lat is: 38.912799
That is indicating to me that the code inside the await block is executing last. I have the same results without the async/await. How can I get the subscribe code to execute first and make the other code wait until my lat and lng have a value? Right now they only have values inside the subscribe block, but I can't put a return line inside like this answer suggests.
I have read that await/async in Angular is essentially the same thing as a promise and callback. I am treating the result of this async getCoordinates function as a promise already by using .then():
service.getCoordinates(this.address).then(
(val) => this.coordinates = val,
(err) => console.log(err)
);