koa源码分析-co模块以及thunk

Thunk以及CO模块

co4.0之前都是返回的thunk函数
之后的都是返回promise

thunk

thunk:在 JavaScript 语言中,Thunk 函数替换的是将多参数函数,替换成单参数的版本,且只接受回调函数作为参数。

// 正常版本的readFile(多参数版本)
fs.readFile(fileName, callback);

// Thunk版本的readFile(单参数版本)
var readFileThunk = Thunk(fileName);
readFileThunk(callback);

var Thunk = function (fileName){
     return function (callback){
    return fs.readFile(fileName, callback); 
  };
};

生产环境中,可以使用thunkify将函数转换为thunk 函数

问题:

  1. 为什么node 里面大部分的callback都是第一个参数是err呢?

  2. 为什么要做thunk 转换呢?

  3. 在redux里面也有thunk middleware,这个thunk是什么意思呢?

CO 模块

co的原理很简单,就是将传入的generator function 转换为一个thunk,并且转换后thunk 的generator的每个value值作为下一个状态的输入

function co(fn) {

   var isGenFun = isGeneratorFunction(fn);

   return function (done) {//返回的thunk函数,done 作为回调函数
        var ctx = this;
    
        // in toThunk() below we invoke co()
        // with a generator, so optimize for
        // this case
        var gen = fn;
    
        //gen function 转换为generator
        if (isGenFun) {
          var args = slice.call(arguments), len = args.length;
          var hasCallback = len && 'function' == typeof args[len - 1];
          done = hasCallback ? args.pop() : error;
          gen = fn.apply(this, args);
        } else {
          done = done || error;
        }
        //函数执行的时候就会执行next函数,进入函数体里面
        next();

        // #92
        // wrap the callback in a setImmediate
        // so that any of its errors aren't caught by `co`
        function exit(err, res) {
          setImmediate(done.bind(ctx, err, res));
        }

        function next(err, res) {
          var ret;
    
          // multiple args
          if (arguments.length > 2) res = slice.call(arguments, 1);
    
          // error
          if (err) {
            try {
              ret = gen.throw(err);
            } catch (e) {
              return exit(e);
            }
          }
    
          // ok
          if (!err) {
            try {
              ret = gen.next(res);
            } catch (e) {
              return exit(e);
            }
          }
    
          // done
          if (ret.done) return exit(null, ret.value);
    
          // normalize
          ret.value = toThunk(ret.value, ctx);
    
          // run
          if ('function' == typeof ret.value) {
            var called = false;
            try {
            
              //比如执行yield readFile('test.json'), ret.value就是readFile函数,函数接受一个callback,callback调用next方法,讲readFile的结果传入了next函数
              ret.value.call(ctx, function(){
                //这里可以防止next函数被多次执行
                if (called) return;
                called = true;
                next.apply(ctx, arguments);
              });
            } catch (e) {
              setImmediate(function(){
                if (called) return;
                called = true;
                next(e);
              });
            }
            return;
          }
    
          // invalid
          next(new Error('yield a function, promise, generator, array, or object'));
        }
      }
}

通过上面的co源码分析,可以看下面的例子

co(function *() {
    var file = yield readFile('test.json');
    
     //这里的file是通过gen.next() 赋值的
    console.log(file);
    
    var ret = yield writeFile(file, 'dest.json');
    
    console.log(ret);    
})

了解了这些基本概念后就可以进入koa的源码阅读了,具体的可以参考下一篇。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值