我想知道all([...effects])
和all(effects)
之间的区别
api中有all(effects)
的注释,但我没有得到
注意 并行运行Effects时,中间件将挂起Generator,直到发生以下情况之一:
所有效果均成功完成:使用包含所有效果结果的数组恢复生成器。
其中一种效果在所有效果完成之前就被拒绝了:在生成器内部抛出了拒绝错误。
答案 0 :(得分:0)
如果您以前使用过promise,则运行all([call(effect1), call(effect2), call(effect3)])
类似于Promise.all或jQuery's $.when。
在所有文档中,有两种语法,唯一的区别是它们返回结果数组或结果对象。
all([effectA, effectB])
:https://github.com/redux-saga/redux-saga/tree/master/docs/api#alleffects---parallel-effects all({ a: effectA, b: effectB })
:https://github.com/redux-saga/redux-saga/tree/master/docs/api#alleffects 使用这两种语法时,redux-saga会并行运行每个效果,当它们全部完成后,它将以数组或对象形式返回结果。
// all([...effects]) - returns an array of results
const [customers, products] = yield all([
call(fetchCustomers),
call(fetchProducts)
])
// all({ a: effectA, b: effectB }) - returns an object of results
const { customers, products } = yield all({
customers: call(fetchCustomers),
products: call(fetchProducts)
})
在这两个示例中,redux saga将立即运行fetchCustomers和fetchProducts,并且当它们都完成后,它将把结果返回给您的saga。
如果任何效果失败或引发错误,则redux-saga会将错误返回给您的传奇/生成器,您必须使用try/catch
与顺序运行效果相比,并行运行效果看起来像这样
// parallel
1. run effect A
2. run effect B
3. wait for responses... (imagine this takes 1 second)
4. get result B
5. get result A
6. continue saga
// sequentially
1. run effect A
2. wait for response.... (imagine this takes 1 second)
3. get result A
4. run effect B
5. wait for response... (wait another second)
6. get result B
7. continue saga