Home > Enterprise >  Sequential Async calls returning undefined
Sequential Async calls returning undefined

Time:01-01

I have an async function that calls multiple async calls in sequential order. However, it is returning undefined despite using the async and await keywords

Flow: currentPosition runs first then coordinates runs next then I can get the latitude and longitude of the coordinates

public async getAddressOfCurrentLocation () {
    const currentPosition = await this.trackCurrentPosition() 
    const coordinates = await this.getCoordinates(currentPosition); // returns undefined, should return [lat, long in numerical format]
    const latitude = await coordinates[0];
    const longitude = await coordinates[1];

    let options: NativeGeocoderOptions = {
      useLocale: NATIVE_GEOCORDER_OPTIONS.USE_LOCALE,
      maxResults: NATIVE_GEOCORDER_OPTIONS.MAX_RESULTS
    };

    const address = this.getAddressUsingCoordinates(latitude, longitude, options);
    return address;
  }
  
  
  private async trackCurrentPosition() {
    return await this.geolocationImplService.trackCurrentPosition()
  }
  
  private async getCoordinates(position: Observable<Geoposition | PositionError>) {
    return await this.geolocationImplService.getCoordinates(position) 
  }
  
  
  // ----------- geolocationImplService methods------------
  public async trackCurrentPosition() {
    return this.geolocation.watchPosition();
  }
  
  public async getCoordinates (position: Observable<Geoposition | PositionError>) {
    position.subscribe( (positionData) => {
      let result = [0,0]
      if ("coords" in positionData) {
          result[0] = positionData.coords.latitude;
          result[1] = positionData.coords.longitude; 
          return result
      }
      return result
    })
  }
  
  

How do i solve this issue?

CodePudding user response:

The return is in a callback, not in the method itself. Therefore, you are not returning from the method (you are only returning from the callback). You can wrap the subscribe call in a promise, and then return that promise like this:

  public async getCoordinates (position: Observable<Geoposition | PositionError>) {
    return new Promise((resolve) => {
      position.subscribe((positionData) => {
        let result = [0,0]
        if ("coords" in positionData) {
          result[0] = positionData.coords.latitude;
          result[1] = positionData.coords.longitude; 
          return resolve(result);
        }
        return resolve(result);
      });
    });
  }

Calling resolve with the value you want the promise to resolve to. This is called "promisification" which you can read more about here.

  • Related