Русский перевод Redux Saga
  • Главная страница
  • Содержание
    • Главная страница
    • 1. Введение
      • 1.1 Руководство для начинающих
      • 1.2 Предпосылки Saga
    • 2. Основные концепции
      • 2.1. Использование хелперов Saga
      • 2.2 Декларативные эффекты
      • 2.3 Отправка действий
      • 2.4 Обработка ошибок
      • 2.5 Распространёная абстрация: Эффект
    • 3. Продвинутые концепции
      • 3.1 Получение будущих действий
      • 3.2 Неблокирующие вызвы
      • 3.3 Выполнение задач параллельно
      • 3.4 Выполнение гонки между несколькими эффектами
      • 3.5 Последовательность Sagas с использованием yield*
      • 3.6 Композиция Sagas
      • 3.7 Отмена задач
      • 3.8 Модель форвка redux-saga
      • 3.9 Общие паттерны параллелизма
      • 3.10 Примеры тестирования Sagas
      • 3.11 Подключение Sagas к внешнему входу/выходу
      • 3.12 Использование каналов
      • 3.13 Шаблоны корневой саги
    • 4. Рецепты
    • 5. Внешние ресурсы
    • 6. Исправление проблем
    • 7. Глоссарий
    • 8. Справочник API
Powered by GitBook
On this page
  1. Содержание
  2. 3. Продвинутые концепции

3.4 Выполнение гонки между несколькими эффектами

Sometimes we start multiple tasks in parallel but we don't want to wait for all of them, we just need to get the winner: the first one that resolves (or rejects). The race Effect offers a way of triggering a race between multiple Effects.

The following sample shows a task that triggers a remote fetch request, and constrains the response within a 1 second timeout.

import { race, call, put, delay } from 'redux-saga/effects'

function* fetchPostsWithTimeout() {
  const {posts, timeout} = yield race({
    posts: call(fetchApi, '/posts'),
    timeout: delay(1000)
  })

  if (posts)
    yield put({type: 'POSTS_RECEIVED', posts})
  else
    yield put({type: 'TIMEOUT_ERROR'})
}

Another useful feature of race is that it automatically cancels the loser Effects. For example, suppose we have 2 UI buttons:

  • The first starts a task in the background that runs in an endless loop while (true) (e.g. syncing some data with the server each x seconds).

  • Once the background task is started, we enable a second button which will cancel the task

import { race, take, call } from 'redux-saga/effects'

function* backgroundTask() {
  while (true) { ... }
}

function* watchStartBackgroundTask() {
  while (true) {
    yield take('START_BACKGROUND_TASK')
    yield race({
      task: call(backgroundTask),
      cancel: take('CANCEL_TASK')
    })
  }
}

In the case a CANCEL_TASK action is dispatched, the race Effect will automatically cancel backgroundTask by throwing a cancellation error inside it.

Previous3.3 Выполнение задач параллельноNext3.5 Последовательность Sagas с использованием yield*

Last updated 6 years ago