【发布时间】:2021-04-24 18:50:29
【问题描述】:
这里是新的 JS 程序员,但仍在尝试理解 async 和 await。以下简单示例旨在检索用户的位置,然后更新全局变量。我意识到我必须点击“允许位置访问”弹出窗口,但为什么程序直到发生这种情况才暂停?
相反,回调被(显然)永远跳过。也就是说,永远不会有任何输出字符串“In setUserLocation”,最终打印出来的userLocation的值与原始值相同。控制台中没有显示未捕获的错误(我确实在原始代码中进行了错误检查)。
编辑:我向getCurrentPosition 添加了一个错误处理程序回调。基本上,如果我在提示允许访问位置时单击“阻止访问”,它就会被调用。否则程序和以前一样。
var userLocation = {lat: "40.0", lon: "-90.0", name: "Default Location"}
function setUserLocation(position) { // callback function
console.log("In setUserLocation") // never executed -- why?
lat = position.coords.latitude.toString();
lon = position.coords.longitude.toString();
userLocation.lat = lat ;
userLocation.lon = lon ;
userLocation.name = "New Location" ;
console.log(userLocation) ;
}
function failedLocation() {
console.log("Something went wrong")
}
async function retrieveLocation() {
console.log(userLocation) ;
console.log("Getting location") ;
await navigator.geolocation.getCurrentPosition(setUserLocation,failedLocation);
console.log("Got location") ;
console.log(userLocation) ;
}
retrieveLocation() ;
【问题讨论】:
-
getCurrentPosition立即返回,并通过调用回调“返回”其结果。至于为什么不调用回调,我建议添加一个错误回调来检查。 -
为什么要异步?从回调中取出异步。那它有用吗?
-
await navigator.geolocation.getCurrentPosition(setUserLocation);- 这不会等待setUserLocation函数 - 而是等待不返回承诺的getCurrentPosition方法,所以await在这种情况下是没用的。将setUserLocation函数设为async也是不必要的,因为您没有在其中使用await关键字。 -
@Reality 不,不起作用。
标签: javascript async-await navigator