AXIOS:如何在请求失败的情况下并发运行http请求并获取所有请求事件的结果 [英] AXIOS: how to run http requests concurrently and get the result of all requests event if a request fails

查看:363
本文介绍了AXIOS:如何在请求失败的情况下并发运行http请求并获取所有请求事件的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使服务器并发地获取请求,为了做到这一点,我编写了以下功能.

I am trying to make server get requests concurrently, in order to do that I have written the following function.

问题

如果单个呼叫失败,那么我将无法获得其余请求的响应.

If a single call is failing then I am not able to get the response of rest of the requests.

export const getAll = async (collection) => {
    return new Promise((resolve, reject) => {
        const requests = collection.map(req => {
            const config = {
                headers: req.headers,
                params: req.params
            }
            return axios.get(req.url, config);
        })

        axios.all(requests)
            .then(axios.spread((...args) => {
                // all succerss
                resolve(args);
            }))
            .catch(function (error) {
                // single call fails and all calls are lost
                reject(error)
            });
    })
}

是否有可能获得所有请求的结果,无论请求失败还是成功?

Is it possible to get the result of all requests whether it fails or success?

推荐答案

换句话说,即使请求失败,您也想采取其余代码,例如请求成功.

In other words even if request fails you want to act rest of the code like request has succeed.

让我们假设响应不能为null.然后,我们捕获到请求的错误并在这种情况下返回null进行请求.

Let's assume that response cannot be null. Then we catch request's error and return null in this case for request.

export const getAll = async (collection) => {
    const requests = collection.map(req => {
        const config = {
            headers: req.headers,
            params: req.params
        };
        return axios.get(req.url, config).catch(() => null);
    })
    return axios.all(requests);
}

因此,如果您拥有catch()并且它不会引发异常,则所有以后的代码工作,例如Promise已解决,都不会被拒绝.

So if you have catch() and it does not throw exception all later code works like Promise has been resolved not rejected.

还请注意,您不需要从async函数显式返回Promise,因为它会自动发生.更重要的是:由于函数内部没有await,因此实际上不需要将其标记为async.最后,axios.all返回Promise,因此您不需要手动resolve/reject Promise.

Also note you don't need to return Promise explicitly from async function because it happens automatically. Even more: since you don't have await inside the function you actually don't need it to be marked as async. And finally axios.all returns Promise so you don't need to resolve/reject Promise manually.

这篇关于AXIOS:如何在请求失败的情况下并发运行http请求并获取所有请求事件的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆