简体   繁体   中英

How can I make the await subscribe block complete before executing next line of code?

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)
);

Angular's http service returns an Observable . You can convert this to a promise by using the rxjs toPromise operator:

import 'rxjs/add/operator/toPromise';

await this.http.get(url).toPromise().then()
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM