zoukankan      html  css  js  c++  java
  • 实现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;

              

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

  • 相关阅读:
    背景100%显示
    你还在用Html.PartialAsync? 教你更简单一招搞定
    记一次TokuMX数据库集群恢复
    使用SolrNet访问Solr-5.5.0
    从注册表中删除打印机列表中的打印机
    DEV之GridControl常用设置
    在Devexpress中设置按钮列(无需写代码)
    Sql中获取表结构(字段名称,类型,长度,说明)
    DevExpress之ChartControl基本用法
    SQL Server类型与C#类型对应关系[转]
  • 原文地址:https://www.cnblogs.com/ztwBlog/p/6286136.html
Copyright © 2011-2022 走看看