dva中effects核心模擬實現(xiàn)

最近師兄搞了一下螞蟻金服的 ant-design提供的后臺模板框架(基于react)由于這個模板使用的是dva框架,里面各種ES6/ES7的新思想,于是小研究了一下effects。主要是模擬effetcs的異步機制。

ant官方栗子:

export default {
  namespace: 'puzzlecards',
  state: {
    data: [],
    counter: 0,
      },
//+++++++++++++++++++++++++++主要實現(xiàn)一下功能+++++++++++++++++++++++++++++++++++++++++
  effects: {
    *queryInitCards(_, sagaEffects) {
      const { call, put } = sagaEffects;
      const endPointURI = 'https://08ad1pao69.execute-api.us-east-1.amazonaws.com/dev/random_joke';

      const puzzle = yield call(request, endPointURI);
      yield put({ type: 'addNewCard', payload: puzzle });

      yield call(delay, 3000);

      const puzzle2 = yield call(request, endPointURI);
      yield put({ type: 'addNewCard', payload: puzzle2 });
    }
  },
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  reducers: {
    addNewCard(state, { payload: newCard }) {
      const nextCounter = state.counter + 1;
      const newCardWithId = { ...newCard, id: nextCounter };
      const nextData = state.data.concat(newCardWithId);
      return {
        data: nextData,
        counter: nextCounter,
      };
    }
  },
};

師兄實現(xiàn)的核心代碼

                let url = "http://xxxx";
                let param = { name: "xx", age: 22 };

                console.log("before fetch<<<<<<<<<<<<<<<");


                let generatorOutter = {
                        effects: {
                                * httpGet(_, sagaEffects) {
                                        const { _call, _put } = sagaEffects;
                                        let _param = { url: url, param: param }
                                        let res = yield _call(_httpGet, _param);
                                        console.log(res, "1",processId);
                                        yield _put(callback, res,processId);
                                        console.log(res, "2",processId);
                                        yield _call((param)=>{
                                                console.log("this is not a Promise fnc",processId);
                                                console.log("normal fnc param:",param,processId);
                                        },{ppip:processId})
                                },
                        }
                }
                //數(shù)據(jù)回調(diào)方法
                function callback(resData) {
                        console.log(">>>>>>>>>回調(diào)獲取的數(shù)據(jù)<<<<<",processId);
                        console.log(resData,processId);
                }
                //主入口
                let main = function () {
                        let generator = generatorOutter.effects;
                        for (let fnc in generator) {
                                let _step = generator[fnc](_, sagaEffects);
                                sagaEffects.setStep(_step);
                                _step.next();
                        }
                }

                let sagaEffects = {
                        step: new Object(),
                        setStep: function (_step) {
                                this.step = _step;
                        },
                        /*getStep: function () {
                                return this.step;
                        },*/
                        _call:  function (fnc, param) {
                                let step = sagaEffects.step;
                                if (sagaEffects._chargePromise(fnc)) {
                                        console.log("傳入Promise",processId);
                                        fnc(param).then(res => {
                                                if (step) step.next(res);
                                        })
                                } else {
                                         sagaEffects._async_call(fnc, param).then((res)=>{
                                                        if (step) step.next(res);
                                        });   
                                }
                        },
                        _put: function (callback, param) {
                                sagaEffects._async_call(callback, param).then((res)=>{
                                        sagaEffects.step.next(res);  
                                }); 
                        },
                        _async_call:async function(fnc, param){
                                return await  fnc(param);
                        }, 
                        _chargePromise(fnc) {
                                if (fnc !== null && ( typeof fnc === 'function') &&typeof fnc.then === 'function') 
                                return true;
                                return false;
                        },
                        _closeGenerator(){}
                }
                
                async function _httpGet({url, param}) {
                        url = handlerParams(url, param);
                        try {
                                const response = await fetch(url, { credentials: 'include', method: 'GET' });
                                return await response.json();
                        } catch (e) {
                                console.log(e);
                        }
                }

                //開始測試
                main();

看下效果,我同時調(diào)用了6次分別傳入不同的id以區(qū)別,id順序不是1-6說明異步有效

image.png

看下網(wǎng)絡請求,同時發(fā)起

image.png

End

這里我主要實現(xiàn)了sagaEffects中的call和put方法,也就是傳入的方法的執(zhí)行和返回數(shù)據(jù),ES6的異步還是很有意思的,代碼簡潔了不少。
2018-11-19

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容