Do not fail whole task even if one of promises rejected

旧巷老猫 提交于 2020-12-30 08:17:05

问题


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.

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

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.


回答1:


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; // **
      }
    })()
  )
);

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

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



来源:https://stackoverflow.com/questions/63619471/do-not-fail-whole-task-even-if-one-of-promises-rejected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!