应在3次尝试中检索位置的getLocation()函数将返回undefinednavigator.geolocation.getCurrentPosition()返回正确的位置,但是问题出在promise处理中。

问题显然是我在诺言中称诺言。我不允许在已经声明为awaitgeolocate()中使用async关键字。

原始通话:

var getLocationPromise = this.getLocation();
// Do something...
location = await getLocationPromise;


getLocation()

  async getLocation() {
    return new Promise((resolve, reject) => {
      var geolocate;
      for (let i=0; i<3; i++) {

        geolocate = this.geolocate();

        try {
            var location = geolocate;//CAN'T USE AWAIT INSIDE ASYNC...
            resolve(location);
        } catch(err) {
            continue;
        }
      }
      reject("Max geolocation attempts");
    });
  }


geolocate()

  async geolocate() {
    return new Promise((resolve, reject) => {

      navigator.geolocation.getCurrentPosition(
        (position) => {
          resolve(position);
        },
        (err) => {
          reject(err);
        },
        {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
      );
    });
  }

最佳答案

只要在声明为异步的函数中包含以下内容

var getLocationPromise = this.getLocation();
// Do something...
location = await getLocationPromise;


应该是可以的

查看getLocation / geolocate,除非您需要单独的geolocate方法,否则应该可以将它们组合并简化为

getLocation() {
    var geolocate = () =>
        new Promise((resolve, reject) =>
            navigator.geolocation.getCurrentPosition(resolve, reject, {
                enableHighAccuracy: true,
                timeout: 20000,
                maximumAge: 1000
            });
        );
    // this function will "retry" the supplied function (fn) cont times
    var limitedPromiseRetry = (fn, cont) => fn().catch(err => cont > 0 ? limitedPromiseRetry(fn, cont-1) : Promise.reject('Max number of geolocation attempts'));
    return limitedPromiseRetry(geolocate, 3);
}

07-26 00:20