【问题标题】:How to use Async Wait with HTML5 GeoLocation API?如何通过 HTML5 GeoLocation API 使用异步等待?
【发布时间】:2019-01-21 10:01:06
【问题描述】:

第一个方法返回promise。

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

返回reverseGeoCode 方法的结果。

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

使用自定义类进行 API 调用并返回结果。

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

我是这样称呼的:

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

控制台日志未定义。

【问题讨论】:

  • getAddress 没有return 语句,所以它当然会返回一个解析为undefined的Promise
  • 您的 reverseGeoCode 没有返回任何内容,返回调用在 then() 回调中,这不是外部函数的返回
  • @Quentin return this.reverseGeoCode(url); 这应该在await 之外?
  • @PatrickEvans 我无法将 then 内部的值返回到外部?

标签: javascript asynchronous promise w3c-geolocation


【解决方案1】:

下面的代码显示了类似的问题。尝试重构它。请记住在async 函数中将其与await 一起使用。比如:

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



 

【讨论】:

    【解决方案2】:

    显示的sn-ps有几个问题

    1. getAddress() 实际上并没有 return 任何东西。

    2. 如果使用await,则不需要then(),反之亦然(阻塞 或非阻塞,而不是两者)。

    这是一个正确的版本

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

    您还必须以类似的方式重写reverseGeoCode,例如

    async reverseGeoCode(url) {
      let requestService = new RequestService("json", url);
      return await requestService.call();
    }
    

    【讨论】:

    • 感谢您的回答。我仍然收到undefined
    • 这可能是由`return this.reverseGeoCode(url); `
    • 感谢您的回答,我更像是服务器端开发人员,我的 JS 仍然是基本的,但我想等待结果,然后让应用程序继续尝试将其映射到谷歌地图。感谢您的回答,我能够弄清楚如何在继续之前先让应用“等待”该位置
    猜你喜欢
    • 2019-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-13
    • 2020-07-11
    • 2022-01-23
    • 2023-03-21
    • 1970-01-01
    相关资源
    最近更新 更多