首页 > 解决方案 > Promise 本身就是返回 Promise

问题描述

我正在调用一个getCoordinates()我试图返回实际数据本身而不是承诺的函数。因此,例如,如果我在调用后控制台日志坐标,getCoordinates()我会得到以下信息......

Promise {<pending>}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Object
lat: 32.8866234
lng: -97.1008832
__proto__: Object

但是,我只想从中获取latandlng属性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%'}} />}
    />

  )
}

标签: javascriptreactjsaxioses6-promise

解决方案


这些是我喜欢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%'}} />}
    />
  )
}

推荐阅读