Redux 进阶 -- 优雅的处理 async action

本文目标:但愿经过买进口水果生鲜的例子,和你们探讨一下如何优雅的处理异步的 async actionnode

例子:改善水果店购买流程

在上一篇文章 Redux 入门 -- 处理 async action 中,阿大经过请了一个采购员完成了耗时的进口商品的售卖。git

可是,阿大同时也发现了一个问题:顾客要买水果生鲜的话须要找销售员,要买进口水果生鲜的话要找采购员,这样的话,顾客须要找不一样的人,很麻烦。阿大想了想,能不能让顾客只找销售员,而后销售员若是有需求再找采购员采购呢。github

阿大想到了办法,让销售员把全部的需求都告诉采购员,而后采购员再传递给收银员,这样,若是是须要采购的水果生鲜,就能够独自去处理了,这样就须要把采购员改为这样了:redux

const API = store => {
  
  // 和 收银员 对接的方式
  const next = store.dispatch;
  
  // 接管销售员传来的顾客需求
  store.dispatch = action => {

    // 处理完了以后再对接 收银员
    switch (action.type) {
      case 'BUY_IMPORTED_APPLE': fetching(2000, () => next(action)); break;
      case 'BUY_IMPORTED_EGG': fetching(3000, () => next(action)); break;
      default: next(action);
    }
  }
}

API(store);
复制代码

而后顾客来了以后就都只用找销售员了:app

store.dispatch(buyApple(3));
store.dispatch(buyImportedApple(10));
store.dispatch(buyEgg(1));
store.dispatch(buyImportedEgg(10));
store.dispatch(buyApple(4));
store.dispatch(buyImportedApple(10));
store.dispatch(buyEgg(8));
store.dispatch(buyImportedEgg(10));
// {"fruit":{"apple":3,"importedApple":0},"fresh":{"egg":0,"importedEgg":0}}
// {"fruit":{"apple":3,"importedApple":0},"fresh":{"egg":1,"importedEgg":0}}
// {"fruit":{"apple":7,"importedApple":0},"fresh":{"egg":1,"importedEgg":0}}
// {"fruit":{"apple":7,"importedApple":0},"fresh":{"egg":9,"importedEgg":0}}
// {"fruit":{"apple":7,"importedApple":10},"fresh":{"egg":9,"importedEgg":0}}
// {"fruit":{"apple":7,"importedApple":20},"fresh":{"egg":9,"importedEgg":0}}
// {"fruit":{"apple":7,"importedApple":20},"fresh":{"egg":9,"importedEgg":10}}
// {"fruit":{"apple":7,"importedApple":20},"fresh":{"egg":9,"importedEgg":20}}
复制代码

嗯嗯,这样看起来就一致多了。阿大内心美滋滋~异步

图解

代码地址:redux入门 -- 改善水果店购买流程,直接控制台运行 node ./demo4/index.js 查看效果async

上一篇:Redux 入门 -- 处理 async actionpost

下一篇:Redux 进阶 -- 编写和使用中间件fetch

相关文章
相关标签/搜索