如何基于异步调度的动作执行多个生成器 [英] How to execute multiple generators based on actions dispatched asynchronously
问题描述
我正在尝试分派多个动作,这些动作将触发多个生成器功能.
I am trying to dispatch multiple actions which will trigger multiple generator functions.
点击
dispatch({ type: "ACTION_1", data1});
dispatch({ type: "ACTION_2", data2});
saga.js
function* method1(action){
//...
const response = yield call(api, requestParams);
//...
}
function* method2(action){
//...
const response1 = yield call(api, requestParams1);
//...
//dependent on response1
const response2 = yield call(api, requestParams2);
//...
//dependent on response2
const response3 = yield call(api, requestParams3);
//...
}
function* actionWatcher() {
yield all([
takeLatest("ACTION_1", method1),
takeLatest("ACTION_2", method2),
]);
}
export default function* sagas() {
yield all([actionWatcher()]);
}
OnClick,method1 被调用,我可以看到一个网络调用,控制台上有这个错误Error: Generator is already running
.
OnClick, method1 is called and I can see a network call and there is this error on console Error: Generator is already running
.
我在 actionWatcher()
方法中也尝试过 takeEvery
,同样的错误.
I have tried takeEvery
as well in actionWatcher()
method, same error.
我如何实现这一目标?
推荐答案
根据要求,我们可以创建像这里 method1Saga 和 method2Saga 一样的 saga,所以,我给你一个例子 saga 是如何工作的
As per requirement we can create sagas like here method1Saga and method2Saga is required so, i am giving you one example how saga works
//worker : work for our saga
function* method1(action) {
// api call : if we have many dependent api calls then we can simply add
//one more response2 below response1 and we can use response1 in response2 as well because yield wait until we get our response from server
const response1 = yield call(api, requestParams); // api call which return type and payload
const response2 = ......
yield put(pass_final_response_here); // pass_final_response_here like ( { type : '' , payload : 'your_response' } )
}
//watcher : watch for request
function* method1Saga() {
yield takeLatest("ACTION_1",method1)
}
//你可以按照上面的例子创建你的 method2Saga
// you can create your method2Saga as per above example
function* actionWatcher() {
yield all([
method1Saga(),
//pass your all saga here
]);
}
最后导入 actionWatcher.where 我们正在配置我们的商店,然后运行我们的传奇.喜欢
Finally import actionWatcher.where we are configuring our store and then just run our saga. like
/**
* Store Configuration
*/
import { createStore , applyMiddleware } from 'redux';
import rootReducer from 'your_root_reducer_path';
//middleware
import reduxSaga from 'redux-saga';
//actionWatcherPath
import actionWatcherPath from 'actionWatcherPath'; //
const sagaMiddleware = reduxSaga();
//store
const store = createStore(rootReducer,applyMiddleware(sagaMiddleware));
//run : our actionWatcherPath
sagaMiddleware.run(actionWatcherPath);
export default store;
这篇关于如何基于异步调度的动作执行多个生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!