Redux Saga: добавьте фоновое задание и повторите попытку - PullRequest
0 голосов
/ 15 октября 2019

Я пишу отменяемую сагу, которая выбирает данные каждые 20 секунд в фоновом режиме.

function* continouslyFetchData() {
  while (true) {
    try {
      const response = yield call(getData)
      const json = yield call(response.json)
      if (!json || !json.specialKey) {
        throw new Error(
          `failed to fetch data; bad response: ${JSON.stringify(json)}`
        )
      }
      const specialData = json.specialData[0]
      yield put(setFoo(specialData.foo)))
    } catch (error) {
      console.error('Failed to fetch data, retrying')
      console.error(error)
      throw error
    } finally {
      yield delay(20 * 1000)
    }
  }
}

function* handleFetchData() {
  while (yield take(fetchData.type)) {
    const bgFetchData = yield fork(continouslyFetchData)
    yield take(stopFetchData.type)
    yield cancel(bgFetchData)
  }
}

А вот мой тест, который обрабатывает случаи throw и catch:

{
  const clone = gen.clone()

  const json = {}

  assert({
    given: 'invalid json',
    should: 'throw',
    actual: Try(clone.next, json).message,
    expected: `failed to fetch dai data; bad response: ${JSON.stringify(
      json
    )}`
  })

  assert({
    given: 'nothing',
    should: 'wait for 20 seconds',
    actual: clone.next().value,
    expected: delay(20 * 1000)
  })
}

Моя проблема в том, что этот тест не пройден, потому что по какой-то причине Try(clone.next, json) равно delay(20 * 1000) вместо сообщения об ошибке. Мне нужно это сообщение, чтобы повторно выдать ошибку, но все же подождать 20 секунд, а затем повторить попытку.

Как бы вы написали это?

...