【发布时间】:2018-11-07 19:25:57
【问题描述】:
我正在调用一个函数getCoordinates(),我试图返回实际数据本身而不是承诺。因此,例如,如果我在调用 getCoordinates() 后控制台日志坐标,我会得到以下信息......
Promise {<pending>}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Object
lat: 32.8866234
lng: -97.1008832
__proto__: Object
但是,我只想从getCoordinates() 获取lat 和lng 属性
getCoordinates()
const getCoordinates = (address) => {
const convertedAddress = address.address.replace(/ /g, '+')
return axios.get(`https://maps.googleapis.com/maps/api/geocode/json?address=
${convertedAddress}&key=youwerelikeabrothertomeannie`)
.then(res => { return res.data.results[0].geometry.location })
}
我想将获得的坐标传递到 RegularMap 组件中
正在渲染的组件
function Map ({...props}) {
const coordinates = getCoordinates(props)
console.log(coordinates)
return (
<RegularMap
googleMapURL='https://maps.googleapis.com/maps/api/js?key=jedimaster
loadingElement={<div style={{height: '100%'}} />}
containerElement={<div style={{height: '280px'}} />}
coordinates={coordinates}
mapElement={<div style={{height: '100%'}} />}
/>
)
}
【问题讨论】:
-
“我试图返回实际数据本身而不是承诺。” 那么你还没有理解承诺是如何工作的。要获取 Promise 的数据,请使用
.then:getCoordinates().then(coords => console.log(coords.lat);)。任何需要访问 promise 数据的东西都需要在内部或从then回调中调用。 -
叹了口气。谢谢你引用我的话。让我把它写下来,如果你想把它作为答案,我可以标记它?
-
所有异步内容的规范问答是 stackoverflow.com/questions/14220321/… 。看完之后,你觉得你会想通这个问题吗?如果是,则应将其作为重复项关闭。
标签: javascript reactjs axios es6-promise