【问题标题】:Why is callback function for geolocation (with 'await') never getting called?为什么地理定位的回调函数(带有'await')永远不会被调用?
【发布时间】:2021-04-24 18:50:29
【问题描述】:

这里是新的 JS 程序员,但仍在尝试理解 asyncawait。以下简单示例旨在检索用户的位置,然后更新全局变量。我意识到我必须点击“允许位置访问”弹出窗口,但为什么程序直到发生这种情况才暂停?

相反,回调被(显然)永远跳过。也就是说,永远不会有任何输出字符串“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


【解决方案1】:

getCurrentPosition 不返回任何东西,你必须先“承诺”它:

let getLocation = () => new Promise((resolve, reject) => 
  navigator.geolocation.getCurrentPosition(resolve, reject));

async function main() {
  try {
    console.log('getting location...');
    let location = await getLocation();
    console.log('got location');
    console.log(location)
  } catch (e) {
    console.log('ERROR');
    console.log(e.message)
  }
}


main()

【讨论】:

  • 这对我也不起作用。如果我在位置弹出窗口中阻止访问,我会收到错误消息,但如果我允许,我不会收到控制台输出。
  • @GrantPetty:分享你的操作系统/浏览器版本。
  • 总是一个好主意。我想知道这是否仅仅是浏览器的问题。
  • Chrome 89.0.4389.114,MacOS 11.2.3
  • Chrome 是否在系统偏好设置 > 安全和隐私 > 定位服务中启用?
【解决方案2】:

我的回调函数从未被执行根本的原因显然与我的 Mac 的 Big Sur 下的安全首选项中未选中 Chrome 的位置访问有关。剩下的谜团是为什么手动重新检查没有坚持 - 它一直恢复为未检查。事实证明,这在这里被描述为一个错误:

https://discussions.apple.com/thread/252188240

更新 Chrome 解决了这个问题,现在执行回调。但是,我仍然遇到它没有按所需顺序执行的问题,所以我没有编辑这个问题(这可能与其他来到这里的人有关),我想我会发布一个更新后的新问题(不同)问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-18
    相关资源
    最近更新 更多