在使用Axios时,我应该使用Promises吗?

7 浏览
0 Comments

在使用Axios时,我应该使用Promises吗?

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

app.get('/api/nearbyRecommendations', async (req, res) => {
    if (!req.query) return res.send({ error: '请启用定位以获取推荐信息。' })
    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: '未找到位置。' })
            resolve(response.data)
        }).catch(error => {
            reject(error)
        })
    })
}

如果可能的话,请帮忙指出任何可能改变以遵循最佳实践的地方。

0
0 Comments

在使用Axios时,是否应该使用Promises?

Axios.get已经为你返回了一个promise。如果你还定义了一个async函数,那么意味着返回的promise将再次被包装在一个promise中。所以在你的例子中,你将返回的结果包装了三次。如果你用一个普通的函数替换它,那么在第一个代码片段中使用的方式将保持不变。

resolve和reject是从哪里来的?

有道理,谢谢你的反馈!

好的,我犯了一个复制粘贴错误,我改正了我的回答以反映一个可工作的示例。

如果你只是在catch中记录错误...如果发生错误,getLocationName(lat, lng).then(res...将会收到undefined

你是正确的。最好让错误向上冒泡,并在try catch中处理它,或者像这样记录并重新抛出错误。我已经修改了代码示例以反映第二种情况。

0