JS中間件設(shè)計(jì)模式的深入探討與實(shí)例分析
本文實(shí)例講述了JS中間件設(shè)計(jì)模式。分享給大家供大家參考,具體如下:
中間件作為一些輔助處理功能,應(yīng)用非常廣泛,例如express中間件,redux中間件,koa中間件,那么中間件的設(shè)計(jì)模式到底是怎樣的呢。結(jié)合中間件的使用實(shí)例探討和總結(jié)一下中間件的設(shè)計(jì)思想和一般實(shí)現(xiàn)模式。
仿照redux中間件實(shí)現(xiàn)模式,看如下一個例子:
function fn2(next){ console.log(’執(zhí)行2,返回改造的next之前’) return action => { console.log(’執(zhí)行2’) next(action) }}function fn3(next){ console.log(’執(zhí)行3,返回改造的next之前’) return action => { console.log(’執(zhí)行3’) next(action) }}function fn1(next){ console.log(’執(zhí)行1,返回改造的next之前’) return action => { console.log(’執(zhí)行1’) getData().then( data => { next(action) }) } } function getData(){ return new Promise(resolve => { setTimeout( () => { resolve(true) },3000) })}const next = (action) => { console.log(’action’,action)}// compose([fn1,fn2,fn3])(next)const mm = [fn1,fn2,fn3].reduce(function(a,b,currentIndex,arr){ console.log('a',a) console.log('b',b) return function(...args){ console.log(’args’,[...args][0].toString()) return a(b(...args)) }})(next)(1)
運(yùn)行結(jié)果:這里類似與洋蔥圈模型,但是是先從里向外,再由外向里
執(zhí)行3,返回改造的next之前args action => {console.log(’執(zhí)行3’)next(action) }執(zhí)行2,返回改造的next之前執(zhí)行1,返回改造的next之前執(zhí)行1執(zhí)行2執(zhí)行3action 1
接下來對上面的實(shí)例進(jìn)行簡化:
function fn2(action){ console.log(’執(zhí)行2,返回改造的next之前’) action+2}function fn3(action){ console.log(’執(zhí)行3,返回改造的next之前’) action+1}function fn1(action){ console.log(’執(zhí)行1,返回改造的next之前’) return action+1 } function getData(){ return new Promise(resolve => { setTimeout( () => { resolve(true) },3000) })}const next = (action) => { console.log(’action’,action)}// compose([fn1,fn2,fn3])(next)const mm = [fn1,fn2,fn3].reduce(function(a,b,currentIndex,arr){ console.log('a',a) console.log('b',b) return function(...args){ console.log(’args’,[...args]) return a(b(...args)) }})(1)
這時的中間件只是一層處理邏輯,沒有傳遞初始處理邏輯,所以中間件是單一的,運(yùn)行結(jié)果:
args [ 1 ]執(zhí)行3,返回改造的next之前args [ undefined ]執(zhí)行2,返回改造的next之前執(zhí)行1,返回改造的next之前
抽離通用邏輯,深入到本質(zhì),中間件是對最初處理邏輯函數(shù)進(jìn)行改造,如果沒有,只執(zhí)行自身的邏輯。
1,上面比較單一的就是只有自身邏輯的中間件
2,具有初始處理邏輯函數(shù)next的中間件,需要接受next,返回一個新的next’
感興趣的朋友可以使用在線HTML/CSS/JavaScript代碼運(yùn)行工具:http://tools.jb51.net/code/HtmlJsRun測試上述代碼運(yùn)行效果。
更多關(guān)于JavaScript相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《javascript面向?qū)ο笕腴T教程》、《JavaScript錯誤與調(diào)試技巧總結(jié)》、《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》、《JavaScript遍歷算法與技巧總結(jié)》及《JavaScript數(shù)學(xué)運(yùn)算用法總結(jié)》
希望本文所述對大家JavaScript程序設(shè)計(jì)有所幫助。
相關(guān)文章:
1. Python如何批量生成和調(diào)用變量2. ASP.NET MVC實(shí)現(xiàn)橫向展示購物車3. ASP.Net Core對USB攝像頭進(jìn)行截圖4. .net如何優(yōu)雅的使用EFCore實(shí)例詳解5. ASP.Net Core(C#)創(chuàng)建Web站點(diǎn)的實(shí)現(xiàn)6. python 爬取京東指定商品評論并進(jìn)行情感分析7. python基礎(chǔ)之匿名函數(shù)詳解8. Python獲取B站粉絲數(shù)的示例代碼9. ajax動態(tài)加載json數(shù)據(jù)并詳細(xì)解析10. 通過CSS數(shù)學(xué)函數(shù)實(shí)現(xiàn)動畫特效
