本文介绍了如何将“异步等待"与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 (blockingor 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();
}

这篇关于如何将“异步等待"与HTML5 GeoLocation API结合使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 11:49