等待一个redux-saga

时间:2017-12-04 13:45:28

标签: javascript ecmascript-6 redux-saga

我想在传奇中引入延迟(使用redux-saga)。

我该怎么做?

如果redux-saga提供了API,我也会对如何手动实现它感兴趣。

Request templateRequest = new Request.Builder()
  .url("https://www.example.com/")
  .addHeader(...)
  .build();
Request stackoverflowRequest = templateRequest.newBuilder()
  .url("https://www.stackoverflow.com/")
  .build();
Request googleRequest = templateRequest.newBuilder()
  .url("https://www.google.com/")
  .build();

3 个答案:

答案 0 :(得分:9)

Redux-sagas a special effect为此:

  

延迟(ms,[val])

     

返回一个Promise,它将在ms毫秒后用val。

解析

示例:

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

function* someSaga(input) {
  yield put(someAction())
  yield call(delay, 500)
  yield put(anotherAction())
}

答案 1 :(得分:0)

Source

export function delay(ms, val = true) {
  let timeoutId
  const promise = new Promise(resolve => {
    timeoutId = setTimeout(() => resolve(val), ms)
  })

  promise[CANCEL] = () => clearTimeout(timeoutId)

  return promise
}

答案 2 :(得分:0)

你可以通过承诺实现这一目标:

function sleep(sec) { 
    return new Promise(resolve => setTimeout(resolve, sec*1000)); 
}

function* save({ payload }) {
    yield put(pending());
    yield sleep(2); //wait 2 seconds
    yield put(complete());
}