【问题标题】:Should I use Promises when using Axios? [duplicate]使用 Axios 时应该使用 Promises 吗? [复制]
【发布时间】:2020-01-10 15:42:04
【问题描述】:

axios被描述为基于Promise,那么在使用axios查询数据时是否需要返回一个新的Promise?

app.get('/api/nearbyRecommendations', async (req, res) => {

    if(!req.query) return res.send({ error: 'Please enable location to get recommendations.' })

    try {
        const { longitude, latitude } = req.query
        const locationName = await location.getLocationName(longitude, latitude)
        res.send(locationName)
    } catch (error) {
        res.send(error)
    }
})   

我正在向 MapBox API 发出 GET 请求,但尽管为我的 Axios 请求设置了 catch 块,但我似乎从未收到任何错误,即使我在 .then() 块中抛出了一个新错误。

const getLocationName = async (latitude, longitude) => {
    return new Promise((resolve, reject) => {
        axios.get(`https://api.mapbox.com/geocoding/v5/mapbox.places/${longitude},${latitude}.json?access_token=${darkSkyAPIKey}`, {json: true})
        .then(response => {
            if(!response.data) return reject({ error: 'No location found.' })

            resolve(response.data)
        }).catch(error => {
            reject(error)
        })
    })
}

如果可能,请提供帮助并指出任何可能更改的内容以遵循最佳实践。

【问题讨论】:

  • 在使用 Axios 时是否需要返回一个新的 Promise:没有。 Axios 完全支持 Promise,无需将 Promise 包装在 Promise 中。
  • @ambianBeing 更不用说async 函数无论如何都会隐式返回一个 Promise。
  • @ambianBeing 但是,我返回的 Promise 在正常的 fetch 请求中可以正常工作,对吧?
  • @LeonKho fetch() 也返回一个承诺,因此创建一个新的承诺是上述链接反模式的一部分
  • @LeonKho 是的,应该。话虽如此,返回axios 结果将是一种简洁/干净的方式,并且不易出错。还请阅读@AsafAviv 共享的链接,非常好。

标签: javascript promise async-await axios fetch


【解决方案1】:

你可以不使用异步函数立即返回承诺:

const getLocationName = (latitude, longitude) => {
  return axios.get(`https://api.mapbox.com/geocoding/v5/mapbox.places/${longitude},${latitude}.json?access_token=${darkSkyAPIKey}`, {json: true})
  .then(response => {
      if(!response.data) 
        throw Error('No location found.')
      return response.data;
  }).catch(error => {
      console.log(error);
      throw error;
  })
}

Axios.get 已经向您返回了一个承诺。如果您还将函数定义为 async,则意味着返回的 Promise 将再次包装在 Promise 中。因此,在您的示例中,您将响应三重包装在一个承诺中。如果用普通函数替换成getLocationName函数,第一个代码sn-p中的用法会保持不变。

【讨论】:

  • 解决和拒绝从何而来?
  • @etarhan 有道理,感谢您的反馈!
  • @JaredSmith 好点,我犯了一个复制粘贴错误,调整了我的回复以反映一个工作示例。
  • 如果您所做的只是在 catch 中记录错误...如果确实发生错误,getLocationName(lat, lng).then(res... 将收到 undefined
  • @charlietfl 你是对的。最好让错误冒泡并在try catch中处理它,或者像这样记录它并重新抛出错误。我已经修改了代码示例以反映第二种情况。
猜你喜欢
  • 2017-11-18
  • 2015-06-18
  • 1970-01-01
  • 1970-01-01
  • 2022-01-10
  • 2010-10-10
  • 2011-04-30
  • 2021-09-03
  • 1970-01-01
相关资源
最近更新 更多