【发布时间】: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