简体   繁体   English

使用Redux Saga并行获取数据

[英]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中实现以下行为的正确方法是什么:

  1. An action is dispatched by user interaction. 用户交互将调度操作。
  2. The appropriate listening saga now tries to fetch data from the API, by calling several async methods in parallel. 适当的侦听传奇现在尝试通过并行调用多个异步方法从API获取数据。
  3. Upon every successful response, independently from the rest of the requests, an action is dispatched with the retrieved data (thus updating the UI, etc). 在每次成功响应时,独立于其余请求,将使用检索到的数据调度操作(从而更新UI等)。
  4. Erroneous responses are gathered and then dispatched with a single action once all requests have finished (in order to later show a single error toast, for instance). 收集错误的响应,然后在所有请求完成后通过单个动作调度(例如,为了稍后显示单个错误吐司)。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM