Blog>
Snippets

Parallel Execution with `all` Effect

Showcase parallel execution of multiple sagas using the `all` effect, waiting for all of them to complete before proceeding.
import { all, call } from 'redux-saga/effects';

function* fetchUser() {
  // Imagine we're fetching user information from an API
  const userInfo = yield call(api.fetchUser, 'userId');
  return userInfo;
}

function* fetchPosts() {
  // And here we're fetching posts from an API
  const posts = yield call(api.fetchPosts, 'userId');
  return posts;
}

function* fetchUserAndPosts() {
  // Use 'all' to run multiple sagas in parallel and wait for all of them to complete
  const [user, posts] = yield all([
    call(fetchUser),
    call(fetchPosts)
  ]);
  console.log('User and posts fetched:', user, posts);
}
This code shows how to use the 'all' effect in Redux Saga to perform parallel execution of multiple saga tasks. It defines two sagas, `fetchUser` and `fetchPosts`, each simulating a fetch operation for user information and posts, respectively. The `fetchUserAndPosts` saga then uses `all` to run these two sagas in parallel, waiting for both to complete before proceeding. The results are logged to the console.