redux-saga 就是用来处理上述副作用(异步任务)的一个中间件。它是一个接收事件,并可能触发新事件的过程管理者,为你的应用管理复杂的流程。
const PUT = 'PUT';
function * gen(){
yield {type:PUT,action:{type:"ADD"}};
yield new Promise((resolve)=>setTimeout(resolve,1000));
yield {type:PUT,action:{type:"MINUS"}};
}
function run(gen){
let it = gen();
function next(){
let {done,value:effect} = it.next();
if(!done){
if(effect instanceof Promise){
effect.then(()=>{
if(!done){
next();
}
});
}else{
if(effect.type === PUT){
console.log('派发',effect.action);
}
if(!done){
next();
}
}
}
}
next();
}
run(gen);
function * gen(){
yield 1;
yield 2;
yield 3;
}
let it = gen();
console.log(it[Symbol.iterator]);
let r1 = it.next();
console.log(r1);
//let r2 = it.next();
//let r2 = it.throw();
let r2 = it.return();
console.log(r2);
let r3 = it.next();
console.log(r3);
let r4 = it.next();
console.log(r4);
let EventEmitter = require('events');
let e = new EventEmitter();
e.once('click',(data)=>{
console.log('clicked',data);
});
e.emit('click','data');
e.emit('click','data');
src/index.js
import React from 'react'
import ReactDOM from 'react-dom';
import Counter from './components/Counter';
import {Provider} from 'react-redux';
import store from './store';
ReactDOM.render(<Provider store={store}>
<Counter/>
</Provider>,document.querySelector('#root'));
src\store\sagas.js
import {put,take} from 'redux-saga/effects';
import * as types from './action-types';
function delay(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
function * workerAdd(){
yield delay(1000);
yield put({type:actionTypes.ADD});
}
function * watcherAdd(){
yield take(actionTypes.ASYNC_ADD);
yield workerAdd();
}
export default function* rootSaga() {
yield watcherAdd();
}
src/components/Counter.js
import React,{Component} from 'react'
import {connect} from 'react-redux';
import actionCreators from '../store/actionCreators';
class Counter extends Component{
render() {
return (
<div>
<p>{this.props.number}</p>
<button onClick={this.props.add}>+</button>
</div>
)
}
}
export default connect(
state => state,
actionCreators
)(Counter);
src/store/index.js
import {createStore, applyMiddleware} from 'redux';
import reducer from './reducer';
import createSagaMiddleware from 'redux-saga';
import rootSaga from './sagas';
let sagaMiddleware=createSagaMiddleware();
let store=applyMiddleware(sagaMiddleware)(createStore)(reducer);
sagaMiddleware.run(rootSaga);
window.store=store;
export default store;
src/store/actionCreators.js
import * as types from './action-types';
const actionCreators = {
add() {
return {type:types.ASYNC_ADD}
}
}
export default actionCreators
src/store/action-types.js
export const ASYNC_ADD='ASYNC_ADD';
export const ADD='ADD';
src/store/reducer.js
import * as types from './action-types';
export default function reducer(state={number:0},action) {
switch(action.type){
case types.ADD:
return {number: state.number+1};
default:
return state;
}
}
src\redux-saga\effectTypes.js
export const TAKE = 'TAKE';
export const PUT = 'PUT';
src\redux-saga\effects.js
import * as effectTypes from './effectTypes'
export function take(actionType) {
return { type: effectTypes.TAKE, actionType}
}
export function put(action) {
return { type: effectTypes.PUT, action }
}
src\redux-saga\runSaga.js
import * as effectTypes from './effectTypes'
export default function runSaga(env, saga) {
let { eventEmitter, dispatch } = env;
let it = typeof saga === 'function'?saga():saga;
function next(value) {
let {value:effect,done} = it.next(value);
if (!done) {
if(typeof effect[Symbol.iterator] === 'function'){
runSaga(env,effect);
next();//不会阻止当前saga继续向后走
}else if (effect instanceof Promise) {
effect.then(next);
}else{
switch (effect.type) {
case effectTypes.TAKE:
eventEmitter.once(effect.actionType,next);
break;
case effectTypes.PUT:
dispatch(effect.action);
next();
break;
default:
break;
}
}
}
}
next();
}
redux-saga/index.js
import EventEmitter from 'events';
import runSaga from './runSaga';
export default function createSagaMiddleware() {
let eventEmitter = new EventEmitter();
let boundRunSaga;
function sagaMiddleware({getState,dispatch}) {
boundRunSaga=runSaga.bind(null,{eventEmitter,dispatch,getState});
return function (next) {
return function (action) {
const result = next(action);
eventEmitter.emit(action.type, action);
return result;
}
}
}
sagaMiddleware.run = (saga)=>boundRunSaga(saga);
return sagaMiddleware;
}
+import { put, takeEvery } from '../redux-saga/effects';
import * as actionTypes from './action-types';
+export function* add() {
+ yield put({ type: actionTypes.ADD });
+}
+export default function* rootSaga() {
+ yield fork(add);
+}
src\redux-saga\effectTypes.js
export const TAKE = 'TAKE';
export const PUT = 'PUT';
+export const FORK = 'FORK';
src\redux-saga\effects.js
import * as effectTypes from './effectTypes'
export function take(actionType) {
return { type: effectTypes.TAKE, actionType }
}
export function put(action) {
return { type: effectTypes.PUT, action }
}
+export function fork(saga) {
+ return { type: effectTypes.FORK, saga };
+}
src\redux-saga\runSaga.js
import * as effectTypes from './effectTypes'
export default function runSaga(env, saga) {
let { channel, dispatch } = env;
let it = typeof saga == 'function' ? saga() : saga;
function next(value) {
let { value: effect, done } = it.next(value);
if (!done) {
if (typeof effect[Symbol.iterator] == 'function') {
runSaga(env,effect);
next();
} else {
switch (effect.type) {
case effectTypes.TAKE:
channel.take(effect.actionType, next);
break;
case effectTypes.PUT:
dispatch(effect.action);
next();
break;
+ case effectTypes.FORK:
+ runSaga(env,effect.saga);
+ next();
+ break;
default:
break;
}
}
}
}
next();
}
+import { put, takeEvery } from '../redux-saga/effects';
import * as actionTypes from './action-types';
export function* add() {
yield put({ type: actionTypes.ADD });
}
export default function* rootSaga() {
+ yield takeEvery(actionTypes.ASYNC_ADD,add);
}
src\redux-saga\effects.js
import * as effectTypes from './effectTypes'
export function take(actionType) {
return { type: effectTypes.TAKE, actionType }
}
export function put(action) {
return { type: effectTypes.PUT, action }
}
export function fork(saga) {
return { type: effectTypes.FORK, saga };
}
+export function takeEvery(actionType, saga) {
+ function* takeEveryHelper() {
+ while (true) {
+ yield take(actionType);
+ yield fork(saga);
+ }
+ }
+ return fork(takeEveryHelper);
+}
src\store\sagas.js
+import { put, takeEvery,call } from '../redux-saga/effects';
import * as actionTypes from './action-types';
const delay = ms => new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, ms);
});
export function* add() {
+ yield call(delay,1000);
yield put({ type: actionTypes.ADD });
}
export default function* rootSaga() {
yield takeEvery(actionTypes.ASYNC_ADD, add);
}
src\redux-saga\effectTypes.js
export const TAKE = 'TAKE';
export const PUT = 'PUT';
export const FORK = 'FORK';
+export const CALL = 'CALL';
src\redux-saga\effects.js
import * as effectTypes from './effectTypes'
export function take(actionType) {
return { type: effectTypes.TAKE, actionType }
}
export function put(action) {
return { type: effectTypes.PUT, action }
}
export function fork(saga) {
return { type: effectTypes.FORK, saga };
}
export function takeEvery(pattern, saga) {
function* takeEveryHelper() {
while (true) {
yield take(pattern);
yield fork(saga);
}
}
return fork(takeEveryHelper);
}
+export function call(fn, ...args) {
+ return { type: effectTypes.CALL, fn, args };
+}
src\redux-saga\runSaga.js
import * as effectTypes from './effectTypes'
export default function runSaga(env, saga) {
let { channel, dispatch } = env;
let it = typeof saga == 'function' ? saga() : saga;
function next(value) {
let { value: effect, done } = it.next(value);
if (!done) {
if (typeof effect[Symbol.iterator] == 'function') {
runSaga(env,effect);
next();
}else if(effect.then){
effect.then(next);
} else {
switch (effect.type) {
case effectTypes.TAKE:
channel.take(effect.actionType, next);
break;
case effectTypes.PUT:
dispatch(effect.action);
next();
break;
case effectTypes.FORK:
runSaga(env,effect.saga);
next();
break;
+ case effectTypes.CALL:
+ effect.fn(...effect.args).then(next);
+ break;
default:
break;
}
}
}
}
next();
}
src\store\sagas.js
+import { put, takeEvery,call,cps} from '../redux-saga/effects';
import * as actionTypes from './action-types';
+const delay = (ms,callback)=>{
+ setTimeout(() => {
+ callback(null,'ok');
+ },ms);
+}
export function* add() {
+ let data = yield cps(delay,1000);
+ console.log(data);
yield put({ type: actionTypes.ADD });
}
export default function* rootSaga() {
yield takeEvery(actionTypes.ASYNC_ADD, add);
}
src\redux-saga\effectTypes.js
export const TAKE = 'TAKE';
export const PUT = 'PUT';
export const FORK = 'FORK';
export const CALL = 'CALL';
+export const CPS = 'CPS';
src\redux-saga\effects.js
import * as effectTypes from './effectTypes'
export function take(actionType) {
return { type: effectTypes.TAKE, actionType }
}
export function put(action) {
return { type: effectTypes.PUT, action }
}
export function fork(saga) {
return { type: effectTypes.FORK, saga };
}
export function takeEvery(pattern, saga) {
function* takeEveryHelper() {
while (true) {
yield take(pattern);
yield fork(saga);
}
}
return fork(takeEveryHelper);
}
export function call(fn, ...args) {
return { type: effectTypes.CALL, fn, args };
}
+export function cps(fn, ...args) {
+ return { type: effectTypes.CPS, fn, args };
+}
src\redux-saga\runSaga.js
import * as effectTypes from './effectTypes'
export default function runSaga(env, saga) {
let { channel, dispatch } = env;
let it = typeof saga == 'function' ? saga() : saga;
+ function next(value,isErr) {
+ let result;
+ if (isErr) {
+ result = it.throw(value);
+ } else {
+ result = it.next(value);
+ }
+ let { value: effect, done } = result;
if (!done) {
if (typeof effect[Symbol.iterator] == 'function') {
runSaga(env,effect);
next();
}else if(effect.then){
effect.then(next);
} else {
switch (effect.type) {
case effectTypes.TAKE:
channel.take(effect.actionType, next);
break;
case effectTypes.PUT:
dispatch(effect.action);
next();
break;
case effectTypes.FORK:
runSaga(env,effect.saga);
next();
break;
case effectTypes.CALL:
effect.fn(...effect.args).then(next);
break;
+ case effectTypes.CPS:
+ effect.fn(...effect.args,(err,data)=>{
+ if(err){
+ next(err,true);
+ }else{
+ next(data);
+ }
+ });
+ break;
default:
break;
}
}
}
}
next();
}
src\store\sagas.js
import { put, takeEvery, call, cps, take,all } from '../redux-saga/effects';
import * as actionTypes from './action-types';
+export function* add1() {
+ for (let i = 0; i < 1; i++) {
+ yield take(actionTypes.ASYNC_ADD);
+ yield put({ type: actionTypes.ADD });
+ }
+ console.log('add1 done ');
+ return 'add1Result';
+}
+export function* add2() {
+ for (let i = 0; i < 2; i++) {
+ yield take(actionTypes.ASYNC_ADD);
+ yield put({ type: actionTypes.ADD });
+ }
+ console.log('add2 done ');
+ return 'add2Result';
+}
export default function* rootSaga() {
+ let result = yield all([add1(), add2()]);
+ console.log('done', result);
}
src\redux-saga\effectTypes.js
export const TAKE = 'TAKE';
export const PUT = 'PUT';
export const FORK = 'FORK';
export const CALL = 'CALL';
export const CPS = 'CPS';
export const ALL = 'ALL';
src\redux-saga\effects.js
import * as effectTypes from './effectTypes'
export function take(actionType) {
return { type: effectTypes.TAKE, actionType }
}
export function put(action) {
return { type: effectTypes.PUT, action }
}
export function fork(saga) {
return { type: effectTypes.FORK, saga };
}
export function takeEvery(pattern, saga) {
function* takeEveryHelper() {
while (true) {
yield take(pattern);
yield fork(saga);
}
}
return fork(takeEveryHelper);
}
export function call(fn, ...args) {
return { type: effectTypes.CALL, fn, args };
}
export function cps(fn, ...args) {
return { type: effectTypes.CPS, fn, args };
}
+export function all(iterators) {
+ return { type: effectTypes.ALL, iterators };
+}
src\redux-saga\runSaga.js
import * as effectTypes from './effectTypes'
+export default function runSaga(env, saga,callback) {
let { channel, dispatch } = env;
let it = typeof saga == 'function' ? saga() : saga;
function next(value, isErr) {
let result;
if (isErr) {
result = it.throw(value);
} else {
result = it.next(value);
}
let { value: effect, done } = result;
if (!done) {
if (typeof effect[Symbol.iterator] == 'function') {
runSaga(env, effect);
next();
} else if (effect.then) {
effect.then(next);
} else {
switch (effect.type) {
case effectTypes.TAKE:
channel.take(effect.actionType, next);
break;
case effectTypes.PUT:
dispatch(effect.action);
next();
break;
case effectTypes.FORK:
runSaga(env, effect.saga);
next();
break;
case effectTypes.CALL:
effect.fn(...effect.args).then(next);
break;
case effectTypes.CPS:
effect.fn(...effect.args, (err, data) => {
if (err) {
next(err, true);
} else {
next(data);
}
});
break;
+ case effectTypes.ALL:
+ let {iterators}=effect;
+ let result = [];
+ let completeCount=0;
+ iterators.forEach((iterator,index)=>runSaga(env,effect,(data)=>{
+ result[index]=data;
+ if(++completeCount === iterators.length)
+ next(result);
+ }));
+ break;
default:
break;
}
}
} else {
+ callback && callback(effect);
}
}
next();
}
src\store\sagas.js
+import { put, takeEvery, call, cps, all, take, cancel, fork, delay } from '../redux-saga/effects';
+import * as actionTypes from './action-types';
+export function* add() {
+ while (true) {
+ yield delay(1000);
+ yield put({ type: actionTypes.ADD });
+ }
+}
+export function* addWatcher() {
+ const task = yield fork(add);
+ console.log(task);
+ yield take(actionTypes.STOP_ADD);
+ yield cancel(task);
+}
+export default function* rootSaga() {
+ yield addWatcher();
+}
src\redux-saga\effectTypes.js
export const TAKE = 'TAKE';
export const PUT = 'PUT';
export const FORK = 'FORK';
export const CALL = 'CALL';
export const CPS = 'CPS';
export const ALL = 'ALL';
+export const CANCEL = 'CANCEL';
src\redux-saga\effects.js
import * as effectTypes from './effectTypes'
export function take(actionType) {
return { type: effectTypes.TAKE, actionType }
}
export function put(action) {
return { type: effectTypes.PUT, action }
}
export function fork(saga) {
return { type: effectTypes.FORK, saga };
}
export function takeEvery(pattern, saga) {
function* takeEveryHelper() {
while (true) {
yield take(pattern);
yield fork(saga);
}
}
return fork(takeEveryHelper);
}
export function call(fn, ...args) {
return { type: effectTypes.CALL, fn, args };
}
export function cps(fn, ...args) {
return { type: effectTypes.CPS, fn, args };
}
export function all(effects) {
return { type: effectTypes.ALL, effects };
}
+export function cancel(task) {
+ return { type: effectTypes.CANCEL, task };
+}
src\redux-saga\runSaga.js
import * as effectTypes from './effectTypes';
const CANCEL_TASK = 'CANCEL_TASK';
export default function runSaga(env, saga,callback) {
+ let task = {cancel:()=>next(TASK_CANCEL)};
let { channel, dispatch } = env;
let it = typeof saga == 'function' ? saga() : saga;
function next(value, isErr) {
let result;
if (isErr) {
result = it.throw(value);
+ }else if(value === TASK_CANCEL){
+ result = it.return(value);
} else {
result = it.next(value);
}
let { value: effect, done } = result;
if (!done) {
if (typeof effect[Symbol.iterator] == 'function') {
runSaga(env, effect);
next();
} else if (effect.then) {
effect.then(next);
} else {
switch (effect.type) {
case effectTypes.TAKE:
channel.take(effect.actionType, next);
break;
case effectTypes.PUT:
dispatch(effect.action);
next();
break;
case effectTypes.FORK:
+ let forkTask = runSaga(env, effect.saga);
+ next(forkTask);
break;
case effectTypes.CALL:
effect.fn(...effect.args).then(next);
break;
case effectTypes.CPS:
effect.fn(...effect.args, (err, data) => {
if (err) {
next(err, true);
} else {
next(data);
}
});
break;
case effectTypes.ALL:
let effects=effect.effects;
let result = [];
let complete=0;
effects.forEach((effect,index)=>runSaga(env,effect,(res)=>{
result[index]=res;
if(++complete === effects.length)
next(result);
}));
break;
+ case effectTypes.CANCEL:
+ effect.task.cancel();
+ next();
+ break;
default:
break;
}
}
} else {
callback && callback(effect);
}
}
next();
+ return task;
}
src\store\action-types.js
export const ASYNC_ADD='ASYNC_ADD';
export const ADD='ADD';
+export const STOP='STOP';
src\components\Counter.js
import React,{Component} from 'react'
import {connect} from 'react-redux';
import actions from '../store/actions';
class Counter extends Component{
render() {
return (
<div>
<p>{this.props.number}</p>
+ <button onClick={this.props.stop}>stop</button>
</div>
)
}
}
export default connect(
state => state,
actions
)(Counter);
src\store\actions.js
import * as actionTypes from './action-types';
const actions = {
add() {
return { type: actionTypes.ASYNC_ADD }
},
+ stop() {
+ return { type: actionTypes.STOP }
+ }
}
export default actions