我正在使用打字稿并尝试获取我们目前所处位置的地理位置。我可以获取位置,但我的代码继续而不设置位置。我决定使用await并承诺。我创建了一个看起来像这样的服务:
@Injectable()
export class GoogleMapsService {
private latitude: number;
private longitude:number;
public currentLongitude(): number {
return this.longitude;
}
public currentLatitude(): number {
return this.latitude;
}
constructor() {
this.setCurrentLocation();
}
private async setCurrentLocation() {
let location: GoogleLocation = await this.getLocation();
this.latitude = location.latitude;
this.longitude = location.longitude;
}
private getLocation(): Promise<GoogleLocation> {
let promise = new Promise<GoogleLocation>(() => {
let location = new GoogleLocation();
navigator.geolocation.getCurrentPosition(position => {
location.latitude = position.coords.latitude;
location.longitude = position.coords.longitude;
});
return location;
});
return promise;
}
}
所以我的问题是我在等待时如何设置它。所以当我试图访问它时它就在那里?
答案 0 :(得分:3)
你永远不会在getLocation
中解决你的承诺,所以await
自然会永远等待。从承诺执行者(您传递给new Promise
)的函数中返回一个值并不能解决这个承诺,并注意您尝试返回的内容,您和&#t> #39;在填写坐标之前重新返回too early。
相反,接受promise执行函数中的resolve
和reject
参数并使用它们:
private getLocation(): Promise<GoogleLocation> {
return new Promise<GoogleLocation>((resolve, reject) => {
navigator.geolocation.getCurrentPosition(position => {
if (/*...it didn't work...*/) {
reject(new Error(/*...*/));
} else {
// It worked
const location = new GoogleLocation();
location.latitude = position.coords.latitude;
location.longitude = position.coords.longitude;
resolve(location);
// Maybe you could just `resolve(position.coords)`?
}
});
});
}
附注:如果您宣传地理定位服务,那么您根本不需要new Promise
。