如何将“异步等待"与HTML5 GeoLocation API结合使用?

如何将“异步等待

问题描述:

第一个方法返回promise.

The first method returns 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调用并返回结果.

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

这是我的称呼方式

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

控制台日志未定义.

显示的摘录存在一些问题

There are several problems with the shown snippets

  1. getAddress()实际上没有返回任何东西.

如果使用 await ,则不需要 then(),反之亦然(阻止或非阻塞,不是全部).

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

这是正确的版本

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 ,例如

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