bartekw2213
bartekw2213

Reputation: 81

How to return value to global variable from asyn/await function?

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);

  }
})

Upvotes: 0

Views: 253

Answers (1)

Amar Syla
Amar Syla

Reputation: 3663

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);

  }
})

Upvotes: 2

Related Questions