Redux Saga 异步/等待模式 [英] Redux Saga async/await pattern
问题描述
我在整个代码库中使用 async/await.因此,我的 api 调用是由异步函数定义的
I'm using async/await throughout my codebase. Because of this my api calls are defined by async functions
async function apiFetchFoo {
return await apiCall(...);
}
我想从我的传奇代码中调用这个函数.好像我不能这样做:
I would like to call this function from my saga code. It seems like I can not do this:
// Doesn't work
function* fetchFoo(action) {
const results = await apiFetchFoo();
yield put({type: "FOOS_FETCHED_SUCCESSFULLY", foos: results});
}
但是,这确实有效,并且与 redux saga 文档相匹配:
However, this does work, and matches the redux saga documentation:
// Does work
function* fetchFoo(action) {
const results = yield call(apiFetchFoo);
yield put({type: "FOOS_FETCHED_SUCCESSFULLY", foos: results});
}
这是将 Redux Saga 与 async/await 一起使用的正确方法吗?在 saga 代码中使用这种生成器语法是标准的,而在其他地方使用 async/await 模式吗?
Is this the correct way to use Redux Saga alongside async/await? It is standard to use this generator syntax inside of the saga code, and the async/await pattern elsewhere?
推荐答案
是的,这是使用 Redux-Saga 的标准方式.
Yes, that's the standard way to use Redux-Saga.
你永远不应该直接在 saga-generator 内部调用 await
函数,因为 redux-saga 用于编排副作用.因此,任何时候你想要运行一个副作用,你应该通过一个 redux-saga
效果(通常:call
或 >叉
).如果你直接这样做而不通过 redux-saga
效果产生它,那么 redux-saga
将无法编排副作用.
You should never be calling the await
function directly inside the saga-generator, because redux-saga is for orchestrating the side-effects. Therefore, any time that you want to run a side-effect you should do it by yielding the side-effect through a redux-saga
effect (usually: call
or fork
). If you do it directly without yielding it through a redux-saga
effect, then redux-saga
won't be able to orchestrate the side-effect.
如果你仔细想想,redux-saga 生成器是完全可测试的,不需要模拟任何东西.此外,它有助于保持解耦:如果您的 apiFetchFoo
返回了一个 promise,saga 仍然可以正常工作.
If you think about it, the redux-saga generator is completely testable without the need of mocking anything. Also, it helps to keep things decoupled: if your apiFetchFoo
returned a promise, the saga would still work the same.
这篇关于Redux Saga 异步/等待模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!