在计算距离之前等待用户定位 - 重构为异步函数

Posted

技术标签:

【中文标题】在计算距离之前等待用户定位 - 重构为异步函数【英文标题】:Await for userlocation before calculating distance - Refactor to async function 【发布时间】:2021-06-17 01:25:50 【问题描述】:

在我的应用中,我需要计算当前用户与事件位置之间的距离。

我在以前的项目中使用过这个功能,这对我很有效,因为用户位置是事先确定的。

现在在我的应用程序中有点不同,因为必须在登录主页后立即过滤事件,其中用户位置仍有待确定。

所以我的代码低于asynchronous 以便在userLatuserLon 包含这些值之后开始计算

const [userLat, setUserLat] = useState(localStorage.getItem('userLat'))
const [userLon, setUserLon] = useState(localStorage.getItem('userLon'))


useEffect(() => 
    data?.forEach((el) => 
      Geocode.fromAddress(
        `$el.street $el.houseNumber, $el.zip $el.city`
      )
        .then((res) => 
          let dis = getDistance(
            
              latitude: parseFloat(res.results[0].geometry.location.lat),
              longitude: parseFloat(res.results[0].geometry.location.lon),
            ,
            
              latitude: parseFloat(userLat), // Not available right away
              longitude: parseFloat(userLon), // Not available right away
            
          );
          console.log(dis); // this return NaN since userLat & userLon values aren't available yet
        )
        .catch((err) => console.log(err));
    );
  , [data]);

所以geocode function 应该在userLatuserLon 可用时立即执行。

我尝试了一些方法将其转换为 async function 并尝试将 await 设置为 userLatuserLon 值,但没有成功。

有人能指出正确的方向吗?如何将wait 用于Geocode.fromAddress 直到userLatuserLon 值已由地理定位api 确定?

提前致谢!

【问题讨论】:

【参考方案1】:

虽然您不能 call hooks within conditionals,但您可以在挂钩中包含条件检查!

如果您有需要基于 datauserLatuserLon 运行的效果,则将它们作为依赖项包含在您的效果中并包含检查:

const [userLat, setUserLat] = useState(localStorage.getItem('userLat'));
const [userLon, setUserLon] = useState(localStorage.getItem('userLon'));

useEffect(
  () => 
    // Only calculate distance if coords are available
    if (userLat && userLon) 
      data?.forEach((el) => 
        Geocode.fromAddress(`$el.street $el.houseNumber, $el.zip $el.city`)
          .then((res) => 
            let dis = getDistance(
              
                latitude: parseFloat(res.results[0].geometry.location.lat),
                longitude: parseFloat(res.results[0].geometry.location.lon),
              ,
              
                latitude: parseFloat(userLat),
                longitude: parseFloat(userLon),
              
            );

            // Do something with `dis` here...
          )
          .catch((err) => console.log(err));
      );
    
  ,
  // Re-run effect when these variables update
  [data, userLat, userLon]
);

【讨论】:

天啊@romellem,我的愚蠢错误!这是我尝试过但失败的解决方案,原因如下:res.results[0].geometry.location.lon 必须是 res.results[0].geometry.location.lng 但非常感谢您调查并确认这是解决我的问题的正确方法。干杯!

以上是关于在计算距离之前等待用户定位 - 重构为异步函数的主要内容,如果未能解决你的问题,请参考以下文章

关于javascript闭包与重构

利用线结构光进行三维重构(测距)

Nine——tornado操作之用户图片上传和展示功能代码的重构(由开始的面向编程的思维方式转变为面向对象的思维方式进行代码的重构!)

重构typescript云函数使用promise chaining

用react重构个人网站

异步请求积压可视化|如何 1 分钟内快速定位函数计算积压问题