Javascript AXIOS:如果请求失败,如何并发运行http请求并获取所有请求事件的结果

Javascript AXIOS:如果请求失败,如何并发运行http请求并获取所有请求事件的结果,javascript,reactjs,promise,axios,Javascript,Reactjs,Promise,Axios,我试图使服务器同时获取请求,为此我编写了以下函数 问题 如果一个调用失败,那么我无法获得其余请求的响应 export const getAll = async (collection) => { return new Promise((resolve, reject) => { const requests = collection.map(req => { const config = { hea

我试图使服务器同时获取请求,为此我编写了以下函数

问题

如果一个调用失败,那么我无法获得其余请求的响应

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)
            });
    })
}

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

换句话说,即使请求失败,您也要像请求成功一样执行其余代码

让我们假设响应不能是
null
。然后我们捕获请求的错误,并在本例中为请求返回
null

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已经解决而不是拒绝


还要注意,您不需要从
async
函数显式返回
Promise
,因为它是自动发生的。更重要的是:由于函数中没有
wait
,因此实际上不需要将其标记为
async
。最后是
axios。all
返回
Promise
,因此您不需要手动
解析
/
拒绝
Promise。

我过去的做法是将Promise的返回值包装到一个对象中,该对象要么有
结果
字段,要么有类似的内容和
错误
字段:

export const getAll = async (collection) => {
    const requests = collection.map(req => {
        const config = {
            headers: req.headers,
            params: req.params
        }

        return axios.get(req.url, config)
            //wrap all responses into objects and always resolve
            .then(
                (response) => ({ response }),
                (err) => ({ err })
            );
    });

    return axios.all(requests)
        //note that .then(axios.spread((...args) => {}) is the same as not using
        //spread at all: .then((args) => {})
        .then(axios.spread((...args) => {
            //getAll will resolve with a value of
            //[{ response: {}, err: null }, ...]

            return args;
        }))
        .catch((err) => {
            //this won't be executed unless there's an error in your axios.all
            //.then block

            throw err;
        });
}

另请参阅@skyboyer的帖子,了解他对代码其余部分的一些优点。

以下是基于Andrew解决方案的完整基于node js的示例:

const axios = require('axios');

const getAll = async (collection) => {
    const requests = collection.map(req => {
        const config = {
            // headers: req.headers,
            params: req.params
        }

        return axios.get(req.url, config)
        //wrap all responses into objects and always resolve
            .then(
                (apiResponse) => ({
                    apiResponse
                }),
                (apiError) => ({
                    apiError
                })
            );
    });

    return axios.all(requests)
    //note that .then(axios.spread((...args) => {}) is the same as not using
    //spread at all: .then((args) => {})
        .then(axios.spread((...args) => {
            //getAll will resolve with a value of
            //[{ response: {}, err: null }, ...]

            return args;
        }))
        .catch((axiosError) => {
            //this won't be executed unless there's an error in your axios.all
            //.then block

            throw axiosError;
        });
}

let api1 = {url: "http://localhost:3000/test?id=1001", param: ""};
let api2 = {url: "http://localhost:3000/test?id=1002", param: ""};
let api3 = {url: "http://localhost:3000/test?id=1003", param: ""};
let apis = [api1, api2, api3];

getAll(apis).then((res) => {
        console.log("getAll call finished");
        //console.log(res);
    }
);

它就像一个符咒。我衷心感谢你的回答这是我见过的最优雅的方式。它很漂亮。非常好,尽管他们计划删除它,所以最好使用
Promise.all
而不是
axios.all