作为承诺得到行动的回应(如redux-thunk)

时间:2017-08-20 04:58:02

标签: redux-thunk redux-saga

我正在从redux-thunk转向redux-saga,但却发现了一个缺陷。

使用redux-thunk我有一种非常典型的做法"添加请求":

request

这个行动会回复一个我可以等待的承诺。 requestDownload函数(上面的downloadId)会批准请求,并使用SOME_URL解析,否则如果System.out.println("s1 == s2 ?: " + s1.equals(s2)) 的下载已存在,则会拒绝。

我怎样才能在redux-saga中这样做?似乎行动不能归还任何东西。

由于

1 个答案:

答案 0 :(得分:1)

redux-saga中,您没有使用await,而是将yieldeffects结合使用。

您的代码可能如下所示:

// saga.js

import { call, put } from 'redux-saga/effects'
import { requestDownloadSucceeded, requestDownloadFailed } from './reducer.js'

function* downloadRequestedFlow() {
  try {
    const downloadId = yield call(requestDownload, 'SOME_URL')

    yield put(requestDownloadSucceeded(downloadId))
  } catch(error) {
    yield put(requestDownloadFailed(error))
  }
}


// reducer.js
...
export const requestDownloadSucceeded = downloadId => ({
  type: REQUEST_DOWNLOAD_SUCCEEDED,
  downloadId,
})

export const requestDownloadFailed = error => ({
  type: REQUEST_DOWNLOAD_FAILED,
  error,
})

请注意带有*的生成器函数,该函数允许使用yield。我在这里也使用了常见的REQUESTEDSUCCEEDEDFAILED模式。

我希望这个答案很有帮助。

相关问题