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

Ale*_*usk 3 javascript asynchronous reactjs redux-saga react-redux

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

  • 并发上传限制。这是通过使用一个实现channel在佐贺文档描述

  • 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;
Run Code Online (Sandbox Code Playgroud)

编辑:在这里提炼成沙箱:https : //codesandbox.io/s/cancellable-counter-example-qomw6

ckp*_*pcw 5

我喜欢race用于取消 - 比赛的已解决值是一个具有一个键和值(“获胜”任务的)的对象。redux-saga Race() 文档

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

if (result.cancel) {
  yield call(cancelAll)
}
Run Code Online (Sandbox Code Playgroud)

^ 这可以包含在一个while (true)循环中,因此您应该能够合并原始示例中重复的 fork()。如果需要重新安排worker,可以考虑在里面处理cancelAll

我更喜欢让外部任务处理重新启动,而不是从它们自己的finally块中调用任务。

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