【问题标题】:React Geocode package returns fulfilled Promise object in ReactReact Geocode 包在 React 中返回已完成的 Promise 对象
【发布时间】:2021-11-16 22:21:34
【问题描述】:

我有一个状态,用于在页面加载时接收用户位置。

  const [userLocation, setUserLocation] = useState({
    lat: null,
    lng: null,
    userAddress: ''
  })

我创建了一个 getAddress 函数,该函数旨在使用 react Geocode npm 包根据坐标返回地址的字符串值

  const getAddress = async (lat, lng) => {
    try {
      const res = await Geocode.fromLatLng(lat, lng)
      const address = res.results[0].formatted_address;
      return address

    } catch (err) {
      console.log(err.message)
    }

  }

我的 getUserLocation 函数在页面加载时的 useEffect 中运行

  const getUserLocation = () => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(showPosition);
    } else {
      console.log("Geolocation is not supported by this browser.");
    }
  }

  const showPosition = (position) => {
    setUserLocation({
      ...userLocation,
      lat: position.coords.latitude,
      lng: position.coords.longitude,
      userAddress: getAddress(position.coords.latitude, position.coords.longitude)
    })
  }

我的 userLocation 对象返回如下:

USER LOCATION 
{lat: 43.829601, lng: -79.470408, userAddress: Promise}
lat: 43.829601
lng: -79.470408
userAddress: Promise
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: "126 Seabreeze Ave, Thornhill, ON L4J 9H1, Canada"
[[Prototype]]: Object

我希望返回承诺结果值,显然没有别的。有什么解决办法吗?

【问题讨论】:

  • getAddress 是异步的,所以你需要等待它才能分配它的响应,它不是一个承诺
  • @BrianThompson 目前不是异步的吗?

标签: javascript reactjs promise google-geocoder


【解决方案1】:

因为异步函数返回一个承诺,所以调用它会给你一个承诺,而不是结果。

这里你直接打电话给getAddress

userAddress: getAddress(position.coords.latitude, position.coords.longitude)

但如果你想要结果,你必须让showPosition异步,await 是来自getAddress的结果:

const showPosition = async (position) => {
    setUserLocation({
      ...
      ...
      ...
      userAddress: await getAddress(position.coords.latitude, position.coords.longitude)
    })
  }

【讨论】:

  • 非常感谢朋友
  • 在 JSX 中是否可能出现相同的结果?

    地址:{async () => await getAddress(service.location.lat, service.location.lng)}

  • 试试看!但这只是一个函数声明 - 函数不是有效的反应子级,无论如何除非你真正调用它,否则它不会做任何事情。你不能做某种异步 IIFE (async () => await ...)(),因为那只会返回一个你无论如何都需要等待的承诺......重点:你不能直接在组件内 await.then因为组件不能是异步的。
猜你喜欢
  • 2020-03-20
  • 1970-01-01
  • 1970-01-01
  • 2022-12-22
  • 2020-03-07
  • 2023-03-11
  • 1970-01-01
  • 2020-02-14
  • 1970-01-01
相关资源
最近更新 更多