即使其中一个承诺被拒绝,也不要让整个任务失败 [英] Do not fail whole task even if one of promises rejected

查看:14
本文介绍了即使其中一个承诺被拒绝,也不要让整个任务失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在redux saga中,如果我们想处理多个promise,可以使用all(相当于Promise.all):

In redux saga if we want to handle multiple promises, we can use all (which is equivalent of Promise.all):

yield all(
   users.map((user) => call(signUser, user)),
);

function* signUser() {
   yield call(someApi);
   yield put(someSuccessAction);
}

问题是,即使其中一个承诺(调用)失败,整个任务也会被取消.

The problem is, even if one of the promises (calls) fail, the whole task is cancelled.

我的目标是保持任务活着,即使其中一项承诺失败.

My goal is to keep the task alive, even if one of the promises failed.

在纯 JS 中我可以用 Promise.allSettled 处理它,但是在 redux saga 中正确的方法是什么?

In pure JS I could handle it with Promise.allSettled, but whats the proper way to do it in redux saga?

编辑:仍然没有找到任何合适的解决方案,即使我将 yield all 包装在 try... catch 块中,仍然如果即使其中一个调用失败,整个任务也会被取消.

Edit: still didnt find any suitable solution, even if I wrap the yield all in try... catch block, still if even one of the calls failed, whole task is canceled.

推荐答案

实际上,你应该把你的 Promises 数组改成 Redux-Saga 的 all 方法,你应该像下面这样写:

Actually, you should change your array of Promises to the all method of Redux-Saga, you should write it like below:

yield all(
  users.map((item) =>
    (function* () {
      try {
        return yield call(signUser, item);
      } catch (e) {
        return e; // **
      }
    })()
  )
);

您传递一个自调用生成器函数来处理错误,而不是 throw 使用 return.因此,有两颗星的线(**).

You pass a self-invoking generator function with handling the error and instead of throw use return. hence, the line with two stars(**).

通过使用这种方式,您的所有异步操作都会以已解决状态返回,并且 all 方法从未被拒绝.

By using this way all of your async actions return as resolved and the all method never seen rejection.

这篇关于即使其中一个承诺被拒绝,也不要让整个任务失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆