本文目標:但願經過買進口水果生鮮的例子,和你們探討一下如何優雅的處理異步的
async action
。node
在上一篇文章 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