Within a redux
saga I am sending a half dozen fetch requests to different systems. I want to wait until all those requests return, then do some final processing on the results.
To this end I have an array of promises
, representing each query. I could call Promise.all()
on the array, but this would cause the saga to hang, and thus all events to hang, until the promises return.
I tried creating an async promise
that called promise.all
, then using the redux-effects
Call on that promise, but this also hung.
How can I keep the async
nature of my saga while waiting for the promises to return?
To run all request in parallel you should use the all
effect from redux-saga
. Its analogous to the Promise.all
method you referenced already.
Example:
import { fetchCustomers, fetchProducts } from './path/to/api'
import { all, call } from `redux-saga/effects`
function* mySaga() {
const { customers, products } = yield all({
customers: call(fetchCustomers),
products: call(fetchProducts)
});
// do something with results
}
This is the most straight forward way to run asynchronous operations in parallel and wait for all processes to complete. This approach will not block the javascript event loop. It will only block the remainder of the generator function from running. Other actions in other sagas, and other events (such as clicks), will still be received by your application while the requests are in flight.
Please refer to the official docs for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With