【发布时间】:2017-09-23 15:59:26
【问题描述】:
这是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));
【问题讨论】:
标签: javascript ajax reactjs error-handling redux