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)
如果可能的话,请提供帮助并指出可能进行更改以遵循最佳实践的任何内容。