redux-saga:如何以编程方式为 yield 创建多个 calls/side-effects?

redux-saga: How to create multiple calls/side-effects programmatically for yield?

使用 redux-saga,可以并行执行多个 effect:

import { call } from 'redux-saga/effects'

// correct, effects will get executed in parallel
const [users, repos]  = yield [
  call(fetch, '/users'),
  call(fetch, '/repos')
]

如何以编程方式创建那些 "call" 调用?

我想实现的是:

假设我有一个具有不同参数的数组,我想对每个参数执行对服务器的请求,但与 redux-saga 并行:

const parameters = ['abc', 'def', 'ghi']

const allMyFetchCalls  = parameters.map( (p) => makeCallRequestWithParameter(p) );

makeCallRequestWithParameter 将创建一个函数调用(或在 redux-saga-speech 中:一个效果)call(fetch, param) 就像在 yield call(fetch , 参数)

const resultArray = yield allMyFetchCalls;

这可能吗?如果可能,怎么做?

请注意,call 效果此时不会调用任何东西。 它只是创建普通 JavaScript 对象和 returns。所以你想要的并没有那么难。

import { call } from 'redux-saga/effects'

const params = ['abc', 'def', 'ghi']
const responses  = yield params.map(p => call(fetch, p))

这也可能有效https://github.com/redux-saga/redux-saga/tree/master/docs/api#alleffects

function* mySaga() {
  const { customers, products } = yield all({
    customers: call(fetchCustomers),
    products: call(fetchProducts)
  })
}

因此根据 redux saga docs 截至 2019 年 11 月 17 日的说法,为了使其并行执行,您需要使用 all()

yield all( arrayOfSomething.map( eachSomething => call( myFunction, eachSomething ) ) )

或者如果你想在打电话之前计算一些东西

yield all( arrayOfSomething.map( eachSomething => {
   // do some computations

   // important you return the function which is automatically done 
   // for you in the one line map, this has gotten me a few 
   // times when I am just coding fast
   return call( myFunction, eachSomething ) )
} )