/ / Typescript約束して待っている - 角型、字形、約束

Typescript約束を待っており、角型、字形、約束

私はtypescriptで作業しています。私たちが現在いる場所の地理位置。私は場所を取得することができますが、私のコードは場所を設定せずに続けます。私は待って、約束して使うことにしました。私は次のようなサービスを作成しました:

@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;
}
}

だから私の質問は、私がそれを待っている間、これをどのように設定することができるかということです。だから私はそれにアクセスしようとするとそこにいるのだろうか?

回答:

回答№1の場合は3

あなたは、 getLocation、そう自然に await 永遠に待つ。約束のエグゼキュータの価値を返す (あなたが渡す関数 new Promise 約束を解決しておらず、あなたが何を返そうとしているのか、あなたが戻っているのか 早すぎる座標が記入される前に

代わりに、 resolve そして reject promise executor関数のパラメータを使用してそれらを使用します。

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 まったくそこに。