首页 > 代码库 > KOA中间件实现原理
KOA中间件实现原理
1 //基本原理 2 var empty=(function *(){})(); 3 //中间件3 4 var mid2=function *(){ 5 console.log("2:before yield"); 6 yield empty; 7 console.log("2:after yield"); 8 } 9 //中间件2 10 var mid1=function *(){ 11 console.log("1:before yield"); 12 yield *(mid2()); 13 console.log("1:after yield"); 14 } 15 //中间件1 16 var start=(function *(){ 17 console.log("0:before yield"); 18 yield *(mid1()); 19 console.log("0:after yield"); 20 })(); 21 while(!(start.next().done)){}
结果
0:before yield
1:before yield
2:before yield
2:after yield
1:after yield
0:after yield
//将数组里面的generator函数compose在一起 var mids=[ function *(next){ console.log("0:before yield"); yield 0; yield *next; yield 1; console.log("0:after yield"); }, function *(next){ console.log("1:before yield"); yield 2; yield *next; console.log("1:after yield"); yield 3; }, function *(next){ console.log("2:before yield"); yield 4; yield *next; yield 5; console.log("2:after yield"); } ]; var next = (function* (){})(),i=mids.length; /* while (i--) { next = mids[i].call(null, next);}}*/ for(;i>0;i--){ next=mids[i-1](next);} var ret; while(!(ret=next.next()).done){console.log(ret.value);}
结果
0:before yield
0
1:before yield
2
2:before yield
4
5
2:after yield
1:after yield
3
1
0:after yield
//递归,使用next而非*next跳转到下一个中间件 var mids=[ function *(next){ console.log("0:before yield"); yield 0; yield next; yield 1; console.log("0:after yield"); }, function *(next){ console.log("1:before yield"); yield 2; yield next; console.log("1:after yield"); yield 3; }, function *(next){ console.log("2:before yield"); yield 4; yield next; yield 5; console.log("2:after yield"); } ]; var next = (function* (){})(),i=mids.length; for(;i>0;i--){ next=mids[i-1](next);} function nextGenerator(generatorObj){ var value,item; nextVal(); function nextVal(){ item=generatorObj.next(); if(item.done) {return;} value=item.value; if(isGenerator(value)){ nextGenerator(value); }else console.log(value); nextVal(); } function isGenerator(obj) { return typeof obj.next==‘function‘ && typeof obj.throw==‘function‘; } } nextGenerator(next);
结果
0:before yield
0
1:before yield
2
2:before yield
4
5
2:after yield
1:after yield
3
1
0:after yield
1 //第二个中间件不跳转 2 var mids=[ 3 4 function *(next){ 5 console.log("0:before yield"); 6 yield 0; 7 yield next; 8 yield 1; 9 console.log("0:after yield"); 10 }, 11 function *(next){ 12 console.log("1:before yield"); 13 yield 2; 14 //yield next; 15 console.log("1:after yield"); 16 yield 3; 17 }, 18 function *(next){ 19 console.log("2:before yield"); 20 yield 4; 21 yield next; 22 yield 5; 23 console.log("2:after yield"); 24 } 25 ];
结果
0:before yield
0
1:before yield
2
1:after yield
3
1
0:after yield
KOA中间件实现原理
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。