打字稿承诺并等待

3人

我正在使用打字稿,试图获取我们当前所在位置的地理位置。我可以获得位置,但是我的代码继续运行而没有设置位置。我决定使用等待和承诺。我创建了一个服务,如下所示:

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

所以我的问题是我等待时如何设置它。所以当我尝试访问它时?

TJ人群

您永远不会在中解决您的承诺getLocation,因此自然await会永远等待。从promise执行器(您传递给的函数new Promise返回值并不能解决promise,请注意,您要返回的内容返回的时间太早无法在其上填写坐标。

相反,在您的Promise执行程序函数中接受resolvereject参数并使用它们:

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那里。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章