// thunk函数 function readFile (path, encoding) { return function (cb) { fs.readFile(path, encoding, cb); }; }
1 2
// thunkify var readFile = thunkify(fs.readFile);
例如使用 co 来同步调用 readFile:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
var co = require('co'), fs = require('fs'), Promise = require('es6-promise').Promise; function readFile (path, encoding) { return function (cb) { fs.readFile(path, encoding, cb); }; } co(function* () { var a = yield readFile('a.txt', {encoding: 'utf8'}); console.log(a); // a var b = yield readFile('b.txt', {encoding: 'utf8'}); console.log(b); // b var c = yield readFile('c.txt', {encoding: 'utf8'}); console.log(c); // c return yield Promise.resolve(a + b + c); }).then(function (val) { console.log(val); // abc }).catch(function (error) { console.log(error); });
函数组合(compose)
f 和 g 都是函数,x 是在它们之间通过“管道”传输的值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
var compose = function (f, g) { return function (x) { return f(g(x)); }; }; var toUpperCase = function (x) { return x.toUpperCase(); }; var exclaim = function (x) { return x + '!'; }; var shout = compose(exclaim, toUpperCase); shout("send in the clowns"); // "SEND IN THE CLOWNS!"