This is in continuation to Handling async errors in react redux application
In my react-redux application
How can I handle a case where I make an API call and on its success I want to make another API call and on its success another API call? I would like to handle errors on each calls. Propose a solution without any side effects and anti-pattern.
My Code
// 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));