Blog>
Snippets

Running Tasks in Parallel with Redux Saga

Showcase the use of the `all` effect to run multiple API calls in parallel and wait for all of them to complete in Redux Saga.
import { all, call } from 'redux-saga/effects';
Import all and call effects from redux-saga/effects to be used for parallel execution and making API calls respectively.
function fetchUser(api, userId) { return api.getUser(userId); }
Defines a function to fetch a user's data using an API call, which will be one of the parallel tasks.
function fetchPosts(api) { return api.getPosts(); }
Defines a function to fetch posts, serving as another parallel task in our Saga.
function* mySaga(api) { try { const [user, posts] = yield all([ call(fetchUser, api, 1), call(fetchPosts, api) ]); console.log('User and posts fetched:', user, posts); } catch (error) { console.error('Error fetching data', error); } }
Defines the main Saga. It uses the all effect to run fetchUser and fetchPosts tasks in parallel. It waits for both of them to complete. On success, it logs the user and posts; upon error, it catches and logs the error.