繁体   English   中英

打字稿承诺并等待

[英]Typescript Promise and await

我正在使用打字稿并尝试获取我们目前所处位置的地理位置。 我可以获取位置,但我的代码继续而不设置位置。 我决定使用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;
    }
}

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

你永远不会在getLocation解决你的承诺,所以自然await将永远等待。 从promise执行者中返回一个值(你传递给new 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM