首页 > 解决方案 > React Geocode 包在 React 中返回已完成的 Promise 对象

问题描述

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

  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

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

标签: javascriptreactjspromisegoogle-geocoder

解决方案


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

在这里你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)
    })
  }

推荐阅读