【发布时间】:2017-05-18 12:31:44
【问题描述】:
应该在 3 次尝试中检索位置的 getLocation() 函数改为返回 undefined。 navigator.geolocation.getCurrentPosition() 返回正确的位置,但问题出在 Promise 处理中。
问题显然是我在 Promise 中调用了 Promise。我不允许在 geolocate() 中使用已声明为 async 的 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");
});
}
geolocate():
async geolocate() {
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(
(position) => {
resolve(position);
},
(err) => {
reject(err);
},
{enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
);
});
}
【问题讨论】:
-
await getLocation().then();===await getLocation();- 不是吗? -
它给出了不同的结果。我对
await getLocation();返回undefined有问题,所以我使用await getLocation().then();,这似乎更安全 -
不知道为什么你在
geolocate和getLocation上使用async- 因为这些函数都没有使用await -
//CAN'T USE AWAIT INSIDE ASYNC- 不,这是不对的,你只能在async中使用await -
这就是问题所在,不能
awaitinasync
标签: javascript geolocation promise async-await es6-promise