【发布时间】: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