【问题标题】:Typescript Promise and await打字稿承诺和等待
【发布时间】:2018-03-12 20:50:46
【问题描述】:

我正在使用 typescript 并试图获取我们当前所在位置的地理位置。我可以获取位置,但我的代码在不设置位置的情况下继续。我决定使用 await 和 promise。我创建了一个如下所示的服务:

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

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

【问题讨论】:

  • so my question is how can I set this while i await it - 你想等待什么?
  • 让位置:GoogleLocation = await this.getLocation();

标签: angular typescript promise


【解决方案1】:

你永远不会在getLocation 中解决你的承诺,所以await 自然会永远等待。从 Promise 执行器中返回一个值 (您传递给 new Promise 的函数) 不会解决该 Promise,请注意您要返回的内容,您正在返回 too early ,在坐标填上之前就可以了。

相反,在你的 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

【讨论】:

  • 谢谢你,tj,你能推荐一个我可以阅读的链接吗?
  • @3xGuy: MDN 往往相当不错。 Axel Rauschmayer's blog 非常好(我注意到它现在链接到他完成的在线书籍)...
猜你喜欢
  • 1970-01-01
  • 2019-03-18
  • 2022-01-22
  • 2018-12-19
  • 2018-09-29
  • 2017-03-11
  • 2019-08-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多