使用Axios时应该使用Promises吗?

Leo*_*Kho 2 javascript fetch promise async-await axios

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)
    }
})   
Run Code Online (Sandbox Code Playgroud)

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

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)
        })
    })
}
Run Code Online (Sandbox Code Playgroud)

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

eta*_*han 5

您可以不使用异步函数就立即返回诺言:

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;
  })
}
Run Code Online (Sandbox Code Playgroud)

Axios.get已经向您返回了承诺。如果还将函数定义为异步,则意味着返回的诺言将再次包装在诺言中。因此,在您的示例中,您将响应三重包装为一个承诺。如果将其替换为带有getLocationName常规函数的函数,则第一个代码段中的用法将保持完全相同。

  • 如果您要做的只是记录catch中的错误...`getLocationName(lat,lng).then(res ...`如果确实发生错误,将收到`undefined` (2认同)