[英]Fetch data in parallel using Redux Saga
I wish to know what is the proper way in Redux Saga to achieve the following behavior: 我想知道在Redux Saga中实现以下行为的正确方法是什么:
I have successfully implemented it by using the following pattern (sorry I lack full code examples, it isn't available at the moment): 我已经使用以下模式成功实现了它(抱歉,我缺少完整的代码示例,目前无法使用):
function* fetchData(dataType) {
const resp = yield call(MyApi.fetchData, dataType);
if(!resp.err) {
yield put(fetchDataSuccess, resp.data);
} else {
return resp.err;
}
}
function* mySaga() {
const errors = yield all([
call(fetchData, 'typeOne'),
call(fetchData, 'typeTwo),
call(fetchData, 'typeThree)
]);
// errors contains the returned errors
}
Is it the best way to achieve the desired effect? 这是达到预期效果的最佳方式吗?
You can use fork
effect for sending the requests concurrently https://redux-saga.js.org/docs/advanced/ForkModel.html 您可以使用
fork
效果同时发送请求https://redux-saga.js.org/docs/advanced/ForkModel.html
So your code will become like 所以你的代码会变得像
function* fetchData(dataType) {
const resp = yield call(MyApi.fetchData, dataType);
if(!resp.err) {
yield put(fetchDataSuccess, resp.data);
} else {
return resp.err;
}
}
function* mySaga() {
yield fork(fetchData, 'typeOne');
yield fork(fetchData, 'typeTwo');
yield fork(fetchData, 'typeThree');
}
For error handling, you can throw the error from the generator and handle it in the main saga. 对于错误处理,您可以从生成器中抛出错误并在主传奇中处理它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.