简体   繁体   English

如何从 asyn/await 函数返回值到全局变量?

[英]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.我尝试使用 async/await 功能,但它不起作用。 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);

  }
})

The problem is that navigator.geolocation.getCurrentPosition does not return a Promise .问题是navigator.geolocation.getCurrentPosition不返回Promise That's why you can't use async/await to get its response.这就是为什么你不能使用 async/await 来获得它的响应。 You will have to wrap that into a Promise yourself to be able to use async/await to get the result.您必须自己将其包装到 Promise 中才能使用 async/await 来获得结果。 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);

  }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM