0

I want to return the user's geolocation to the variable so other function can use it later. I tried using async/await function but it doesn't work. What have I done wrong?

// Getting data
class Data {
  static async getLatitude() {
    let latitude = await navigator.geolocation.getCurrentPosition((position) => {
      return position.coords.latitude;
    });
    return latitude;
  }

}


// Site running
window.addEventListener('load', () => {
  if(navigator.geolocation) {
    let latitude = Data.getLatitude();
    console.log(latitude);

  }
})

bartekw2213
  • 81
  • 1
  • 7
  • Your handler needs the keyword await. `await Data.getLatitude()` that will resolve the promise before moving to the next statement – Ruan Mendes Jan 13 '20 at 13:31
  • 3 options you have is, callback, promise or async/await method. It is not practical to store output in a variable while doing async programming. Better look for patterns for working with async functions. – Ali Beyit Jan 13 '20 at 13:32
  • 1
    You're almost there. Try `let latitude = await Data.getLatitude();`. What you have will set `latitude` to the promise that resolves to the latitude rather than the latitude itself. – Patrick Stephansen Jan 13 '20 at 13:32
  • @ali the OP is already trying to use async await, they're just missing a few keywords – Ruan Mendes Jan 13 '20 at 13:33
  • @PatrickStephansen but I can use await only in async function so it doesn't work – bartekw2213 Jan 13 '20 at 13:34
  • My mistake. You also need to make the second argument to the `window.addEventListener` function async: `window.addEventListener('load', async () => {` – Patrick Stephansen Jan 13 '20 at 13:41
  • @PatrickStephansen yeah, I tried this but it is displaying then the undefined value – bartekw2213 Jan 13 '20 at 13:45

1 Answers1

2

The problem is that navigator.geolocation.getCurrentPosition does not return a Promise. That's why you can't use async/await to get its response. You will have to wrap that into a Promise yourself to be able to use async/await to get the result. Here is the full code:

class Data {
  static async getLatitude() {
    return new Promise((resolve, reject) => {
      navigator.geolocation.getCurrentPosition((position) => {
        resolve(position.coords.latitude);
      }, reject);
    });
  }
}

window.addEventListener('load', async () => {
  if (navigator.geolocation) {
    let latitude = await Data.getLatitude();
    console.log(latitude);

  }
})
Amar Syla
  • 3,523
  • 3
  • 29
  • 69