1

I am working with typescript and trying to get the geolocation of where we currently are. I can get the location, but my code continues without setting the location. I decided to use await and promise. I created a service that looks like:

@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. so when i try to access it it is there?

messerbill
  • 5,499
  • 1
  • 27
  • 38
3xGuy
  • 2,235
  • 2
  • 29
  • 51

1 Answers1

4

You never resolve your promise in getLocation, so naturally await will wait forever. Returning a value out of the promise executor (the function you pass into new Promise) doesn't resolve the promise, and note that what you're trying to return, you're returning too early, before the coordinates are filled in on it.

Instead, accept the resolve and reject parameters in your promise executor function and use them:

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)`?
            }
        });
    });
}

Side note: If you promisify the geolocation service, you wouldn't need new Promise in there at all.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • thank you tj, can you suggest a link that I can read up on how to do this? – 3xGuy Mar 12 '18 at 13:18
  • @3xGuy: [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises) tends to be fairly good. [Axel Rauschmayer's blog](http://2ality.com/2014/09/es6-promises-foundations.html) is pretty good (I notice that it now links to an online book he's done)... – T.J. Crowder Mar 12 '18 at 13:24