如何在具有有限并发性和合理取消的redux-saga中实现批处理任务?

时间:2019-06-10 16:29:05

标签: javascript reactjs asynchronous react-redux redux-saga

我正在尝试通过redux-saga实现图像上传。我需要包括的功能是:

  • 并发上传限制。这可以通过将channel用作described in saga docs

  • 来实现
  • 我听的动作,在下面的代码中START_UPLOADS包含(可能很长)文件数组,这些文件分别发布到频道。

  • 我需要能够通过另一项操作CANCEL_ACTION取消所有当前的上载,包括到达任何START_UPLOADS但尚未发布到频道的那些,以及当前正在处理的那些在任何uploadImage工作人员中。

我到达的代码如下。我的问题是cancelAll处理程序是在重新启动传奇的finally块之后执行的,并且总体而言我似乎需要重新启动所有内容。它看起来笨拙且容易出错。您是否可以就Sagas的使用方式提供任何建议?

function* uploadImage(file) {
  const config = yield getConfig();
  const getRequest = new SagaRequest();
  console.log("Making async request here.");
}

function* consumeImages(uploadRequestsChannel) {
  while (true) {
    const fileAdded = yield take(uploadRequestsChannel);
    // process the request
    yield* uploadImage(fileAdded);
  }
}

function* uploadImagesSaga() {
  const CONCURRENT_UPLOADS = 10;
  const uploadRequestsChannel = yield call(channel);
  let workers = [];
  function* scheduleWorkers() {
    workers = [];
    for (let i = 0; i < CONCURRENT_UPLOADS; i++) {
      const worker = yield fork(consumeImages, uploadRequestsChannel);
      workers.push(worker);
    }
  }

  let listener;
  yield* scheduleWorkers();

  function* cancelAll() {
    // cancel producer and consumers, flush channel
    yield cancel(listener);
    for (const worker of workers) {
      yield cancel(worker);
    }
    yield flush(uploadRequestsChannel);
  }

  function* putToChannel(chan, task) {
    return yield put(chan, task);
  }

  function* listenToUploads() {
    try {
      while (true) {
        const { filesAdded } = yield take(START_UPLOADS);
        for (const fileAdded of filesAdded) {
          yield fork(putToChannel, uploadRequestsChannel, fileAdded);
        }
      }
    } finally {
      // if cancelled, restart consumers and producer
      yield* scheduleWorkers();
      listener = yield fork(listenToUploads);
    }
  }

  listener = yield fork(listenToUploads);

  while (true) {
    yield take(CANCEL_ACTION);
    yield call(cancelAll);
  }
}

export default uploadImagesSaga;

编辑:在此处{@ {3}}

中提取到沙箱中

1 个答案:

答案 0 :(得分:2)

我喜欢使用race进行取消-种族的解析值是具有一个键和一个值(“获胜”任务的值)的对象。 redux-saga race() docs

const result = yield race({
  cancel: take(CANCEL_ACTION),
  listener: call(listenToUploads), // use blocking `call`, not fork
});

if (result.cancel) {
  yield call(cancelAll)
}

^这可以包装在while (true)循环中,因此您应该能够合并原始示例中重复的fork()。如果需要重新安排工作人员,则可以考虑在cancelAll内部进行处理。

我宁愿让外部任务句柄重新启动,而不是从自己的finally块中调用任务。

编辑:重构示例沙箱https://codesandbox.io/s/cancellable-counter-example-j5vxr