koa学习笔记三---手写thunkify模块

665 查看

前言

跟co模块高度相关的thunkify模块。

Turn a regular node function into one which returns a thunk, useful for generator-based flow control such as co.

从字面意思来理解,把一个普通的Node函数转换为返回值为thunk的函数。不用深究字面义,thunkify的目的在于把函数分解为两步来执行。第一步传递非回调之外的参数,第二步传递回调函数。

代码示例

module.exports = thunkify;

function thunkify(fn) {
    return function() {
        var args = Array.prototype.slice.call(arguments, 0);
        return function() {
            fn.apply(this, args.concat(arguments[0]));
        }
    }
}

代码很简单,没有错误处理,所有运行时错误会直接抛出。npm上的thunkify模块,看着有点乱糟糟的,可能是我考虑不周全所致。
测试代码如下:

var should = require('should');
var thunkify = require('../thunkify.js');
var path = require('path');
var fs = require('fs');

describe('thunkify', function () {
    it('should resolve right', function (done) {
        var thunk = thunkify(fs.readFile)(path.join(__dirname, '/fixture/fixture'));
        thunk(function(err, value) {
            if (err) return done(err);
            value.toString().should.equal('love is color blind!');
            done();
        });
    });
});

知识点记录

函数内部所有参数可以通过arguments对象来访问。arguments对象与数组很相似,通过数字下标来访问对应的值,但是只具备length属性,不具备其他属性。转化为数组方法很简单:

Array.prototype.slice.call(arguments, 0);

联系方式

QQ:491229492
https://github.com/bornkiller