我正在调用一个函数getCoordinates()
,该函数试图返回实际数据本身而非承诺。因此,例如,如果我在致电getCoordinates()
之后控制台日志坐标,则会得到以下信息...
Promise {<pending>}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Object
lat: 32.8866234
lng: -97.1008832
__proto__: Object
但是,我只想从lat
获得lng
和getCoordinates()
属性
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%'}} />}
/>
)
}
答案 0 :(得分:0)
使您的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`)
}
然后您可以像这样使用它:
getCoordinates('somethinghere')
.then(resp => {
//probably set state here
}).catch(err => {
// probably console log error here
})
答案 1 :(得分:0)
在这些情况下,我喜欢使用async/await
来保证诺言。
如果您有权使用ES7,只需添加这两个字即可解决此问题:
async function Map ({...props}) {
const coordinates = await 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%'}} />}
/>
)
}