处理react-redux应用程序中的promise链接错误

时间:2017-09-23 07:45:46

标签: javascript ajax reactjs error-handling redux

这是Handling async errors in react redux application

的延续

在我的react-redux应用程序中

如何处理我进行API调用的情况及其成功之后我想进行另一次API调用并成功进行另一次API调用?我想处理每个电话的错误。提出一种没有任何副作用和反模式的解决方案。

我的代码

   // sends a request to server 
const makeAsyncCall2 = (arg, response) => {
    const serverArguments = {};

    const req = request
            .post(`${baseUrl}/someotheraction.action`)
            .send(serverArguments)
            .type('form')
            .setAuthHeaders();

    return req.endAsync();
};     

// sends a request to server
const makeAsyncCall1= () => {
    const serverArguments = {};

    const req = request
            .post(`${baseUrl}/somexyz.action`)
            .send(serverArguments)
            .type('form')
            .setAuthHeaders();

    return req.endAsync();
};



   async function makeServerCalls(args, length) {
    // convert args to two dimensional array, chunks of given length [[1,2,3], [4,5,6,], [7,8]]
    const batchedArgs = args.reduce((rows, key, index) => (index % length === 0 ? rows.push([key])
        : rows[rows.length - 1].push(key)) && rows, []);

    const responses = [];

    for (const batchArgs of batchedArgs) {
        responses.push(
            // wait for a chunk to complete, before firing the next chunk of calls
            await Promise.all(
                batchArgs.map((arg) =>
                    request
                        .get(`${baseUrl}/something.cgi`)
                        .query(arg)
                        .endAsync()
                        .then((response) => {
                            makeAsyncCall2(arg, response)
                                .then((res) => console.log(res))
                                .catch((err) => console.log(err))
                            return response;
                        })
                        .catch((error) => {
                            makeAsyncCall2(arg, error)
                                .then((res) => console.log(res))
                                .catch((err) => console.log(err))
                            return error;
                        })
                )
            )
        );
    }

    // wait for all calls to finish
    return Promise.all(responses);
}


// Call starts here 
makeAsyncCall1()
              .then(() => makeServerCalls(args, 3))
              .then((responses) => onAllPromiseResolve(responses));

1 个答案:

答案 0 :(得分:0)

您可以定义单个函数来处理可能的错误或多个函数来单独处理每个可能的错误,使用错误处理函数链.catch()作为每个Promise的参数或函数返回{{ 1}}。