gpt4 book ai didi

javascript - Promise 中的 JS Promise

转载 作者:行者123 更新时间:2023-12-02 13:45:12 24 4
gpt4 key购买 nike

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

问题显然是我在 promise 内调用 promise 。我不允许在已声明为 asyncgeolocate() 中使用 await 关键字。

原始调用:

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

地理定位():

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

关于javascript - Promise 中的 JS Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41460058/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com