[英]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. 我正在订阅Google Maps API以根据地址提取坐标。 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?
我如何才能使订阅代码首先执行,并使其他代码等到lat和lng都具有值? Right now they only have values inside the subscribe block, but I can't put a return line inside like this answer suggests .
现在,它们仅在subscribe块内具有值,但我不能像此答案所示那样在其中放入返回行。
I have read that await/async in Angular is essentially the same thing as a promise and callback. 我已经读到,Angular中的await / async本质上是与promise和callback相同的东西。 I am treating the result of this async getCoordinates function as a promise already by using .then():
我已经通过使用.then()将这个异步getCoordinates函数的结果视为一个承诺:
service.getCoordinates(this.address).then(
(val) => this.coordinates = val,
(err) => console.log(err)
);
Angular's http service returns an Observable
. Angular的http服务返回一个
Observable
。 You can convert this to a promise by using the rxjs toPromise
operator: 您可以使用rxjs
toPromise
运算符将其转换为toPromise
:
import 'rxjs/add/operator/toPromise';
await this.http.get(url).toPromise().then()
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.