实现koa中的generator用法

尽管koa2中已经被async/await代替。但我还是想自个儿着写一个koa1中的generator。

一,

写这个之前,先写一个可以现实,express中next用法的函数:

var event=require('events').EventEmitter;
class App extends event{
     constructor(){
          super();
          this.arr=[],this.i=0;
          this.on('next',data=>{
               let node=this.arr[++this.i];
               if (!node) return ;
                node(this.next);
           })
      }
      next(){
           this.emit('next');
      }
       use(v){
          this.arr.push(v);
      } 
      end(){
           this.arr[this.i](this.next.bind(this));
       }

}

 使用:

var myApp=new App();
myApp.use(next=>{
    console.log('step1');
    next();
})

myApp.use(next=>{
     console.log('step2');
})

myApp.end();

二, 

 很成功。好了。下面写koa里的实现,就直接写function 了。这样写得快些 - -!。。:

function App(){
  let arr=[],i=0;
  let self=this;
  let next=function(){
       if(!arr[++i]) return ;
       self.end();
   };
   this.use=function(fn){
       arr.push(fn);
    }
   this.end=function(){
        let g=arr[i](next);
        let run=function(){                      //run函数执行这个generator;
            let result=g.next();
            if(result.done) return;
            result.value();
run(); } g?run():0; } }

  使用:

var a=new App();
a.use(function* (next){
	console.log('a1');
	yield next;

})
a.use(function* (next){
	console.log('b1');
	yield next;
	console.log('b2');
	yield next;
})
a.use(function* (next){
	console.log('c1');
	yield next;
})
a.use(function(){
	console.log('c2')
})
a.use(function(){
	console.log('c3')
})

a.end();

  返回结果:

        a1;

        b1;

        c1;

        c2;

        b2;

        c3;

          

好的这样大致框架就成功了。其余的可以慢慢进化。。

原文地址:https://www.cnblogs.com/ztwBlog/p/6286136.html