javascript - Promise 本身就是返回 Promise
问题描述
我正在调用一个getCoordinates()
我试图返回实际数据本身而不是承诺的函数。因此,例如,如果我在调用后控制台日志坐标,getCoordinates()
我会得到以下信息......
Promise {<pending>}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Object
lat: 32.8866234
lng: -97.1008832
__proto__: Object
但是,我只想从中获取lat
andlng
属性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%'}} />}
/>
)
}
解决方案
这些是我喜欢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%'}} />}
/>
)
}
推荐阅读
- wordpress - 如何在订单管理面板中更改最小数量
- ruby-on-rails - 连接被拒绝 服务器是否在主机“localhost”(127.0.0.1) 上运行并接受端口 5432 上的 TCP/IP 连接?
- c# - 如何在 C# 中用 for 循环填充这个维度数组?
- r - 如何在情节中更改悬停文本
- linux - `-f` 标志在 shebang 中使用时是什么意思:`#!/bin/bash -f`?
- powershell - 在 powershell 变量中将“TRUE”转换为 1
- asp.net-mvc - 有没有办法将选定的行数据从 Power BI 报告传递到 Asp.net 应用程序
- spring-boot - Spring Kafka 防止重复读取
- docker - 如何防止删除 Kubernetes 工作人员中的 docker 映像?
- java - 是否可以使用 Usage Stats 获取前台活动?