[英]How can I make the await subscribe block complete before executing next line of code?
我正在订阅Google Maps API以根据地址提取坐标。 我的理解是,通过等待订阅行,它应等待该代码块完成,然后再移至以下行。
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;
}
但是,当我运行该应用程序时,我会在控制台中看到以下内容:
outer lat is: undefined
coord lat is: undefined
inner lat is: 38.912799
这向我表明,等待块中的代码正在最后执行。 我没有异步/等待也有相同的结果。 我如何才能使订阅代码首先执行,并使其他代码等到lat和lng都具有值? 现在,它们仅在subscribe块内具有值,但我不能像此答案所示那样在其中放入返回行。
我已经读到,Angular中的await / async本质上是与promise和callback相同的东西。 我已经通过使用.then()将这个异步getCoordinates函数的结果视为一个承诺:
service.getCoordinates(this.address).then(
(val) => this.coordinates = val,
(err) => console.log(err)
);
Angular的http服务返回一个Observable
。 您可以使用rxjs toPromise
运算符将其转换为toPromise
:
import 'rxjs/add/operator/toPromise';
await this.http.get(url).toPromise().then()
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.