9

The first method returns promise.

getCoordinates() {
  return new Promise(function(resolve, reject) {
    navigator.geolocation.getCurrentPosition(resolve, reject);
  });
}

Returns the result of reverseGeoCode method.

async getAddress() {
  await this.getCoordinates().then(position => {
    let latitude = position.coords.latitude;
    let longitude = position.coords.longitude;
    let url = Constants.OSMAP_URL + latitude + "&lon=" + longitude;
    // Reverse geocoding using OpenStreetMap
    return this.reverseGeoCode(url);
  });
}

Uses custom class to make an API call and return the result.

reverseGeoCode(url) {
  let requestService = new RequestService("json", url);
  requestService.call().then(result => {
    return result;
  });
}

This is how I call:

let geoLocation = new GeoLocation();
geoLocation.getAddress().then(r => {
  console.log(r);
});

The console logs undefined.

Bharata
  • 11,779
  • 6
  • 27
  • 42
Maihan Nijat
  • 7,755
  • 6
  • 40
  • 87

2 Answers2

8

There are several problems with the shown snippets

  1. getAddress() doesn't actually return anything.

  2. If await is used, then() is not needed or vice-versa (blocking or non-blocking, not both).

Here is a correct version

async getAddress() {
  // notice, no then(), cause await would block and 
  // wait for the resolved result
  const position = await this.getCoordinates(); 
  let latitude = position.coords.latitude;
  let longitude = position.coords.longitude;
  let url = Constants.OSMAP_URL + latitude + "&lon=" + longitude;

  // Actually return a value
  return this.reverseGeoCode(url);  
}

You'll also have to rewrite reverseGeoCode in a similar fashion, something like

async reverseGeoCode(url) {
  let requestService = new RequestService("json", url);
  return await requestService.call();
}
Lyubomir
  • 17,533
  • 4
  • 51
  • 65
  • Thanks for the answer. I still get `undefined` – Maihan Nijat Aug 14 '18 at 14:08
  • Which is probably caused by ` return this.reverseGeoCode(url); ` – Maihan Nijat Aug 14 '18 at 14:11
  • Thank you for this answer, I'm more of a server side dev and my JS is still basic but I wanted to wait for the results of this before having the app proceed to try to map it onto a Google map. Thanks to your answer I was able to figure out how to make the app "Wait" first for the location before proceeding – Uriahs Victor May 19 '21 at 23:39
3

The code below show similar issue. Try to refactor it. Remember to use it with await in async function. Something like:

window.onload = async () => {

const getCoords = async () => {
        const pos = await new Promise((resolve, reject) => {
          navigator.geolocation.getCurrentPosition(resolve, reject);
        });
    
        return {
          long: pos.coords.longitude,
          lat: pos.coords.latitude,
        };
    };

const coords = await getCoords();
}



 
woodrejs
  • 51
  • 1