Using 'all' and 'race' Effects for Concurrent Operations
Provide an example of using 'all' to run multiple tasks in parallel and 'race' to handle scenarios where only the first completed task is needed.
import { all, race, call } from 'redux-saga/effects';
function* performTasksInParallel() {
try {
yield all([
call(taskOne),
call(taskTwo),
call(taskThree)
]);
// add your code here that should execute after all tasks finished
} catch (error) {
// handle error
}
}
This code snippet uses the 'all' effect to run multiple tasks (taskOne, taskTwo, taskThree) in parallel. If any of these tasks fail, the catch block will catch the error. This is useful when you want all the tasks to complete before proceeding with the next set of operations.
import { race, call, put } from 'redux-saga/effects';
function* performFirstCompleteTask() {
try {
const { task1, timeout } = yield race({
task1: call(longRunningTask),
timeout: call(delay, 5000)
});
if (task1) {
// handle task1 completion
} else {
// handle timeout
yield put({ type: 'TASK_TIMEOUT' });
}
} catch (error) {
// handle error
}
}
This code snippet uses the 'race' effect to run a long-running task against a timeout (delay of 5000 ms). The first one to complete wins the race. If the longRunningTask completes first, the 'task1' branch is executed. If the delay completes first, meaning the longRunningTask took too long, the 'timeout' branch is executed and a 'TASK_TIMEOUT' action is dispatched. This pattern is helpful for handling scenarios where you do not wish to wait indefinitely for a task to complete and would rather proceed depending on whichever completes first.