【问题标题】:Promise is returning promise itselfPromise 本身就是返回 Promise
【发布时间】: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() 获取latlng 属性

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 =&gt; console.log(coords.lat);)。任何需要访问 promise 数据的东西都需要在内部或从 then 回调中调用。
  • 叹了口气。谢谢你引用我的话。让我把它写下来,如果你想把它作为答案,我可以标记它?
  • 所有异步内容的规范问答是 stackoverflow.com/questions/14220321/… 。看完之后,你觉得你会想通这个问题吗?如果是,则应将其作为重复项关闭。

标签: javascript reactjs axios es6-promise


【解决方案1】:

让您的 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
    })

【讨论】:

    【解决方案2】:

    在这些情况下,我喜欢使用 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%'}} />}
        />
      )
    }
    

    【讨论】:

      猜你喜欢
      • 2018-12-14
      • 2021-05-03
      • 1970-01-01
      • 2017-10-31
      • 2021-02-06
      • 2017-03-17
      • 2018-03-25
      • 2021-03-17
      • 2018-08-19
      相关资源
      最近更新 更多