问题描述
在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.
这篇关于即使其中一项承诺被拒绝,也不要让整个任务失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!