Skip to content

Instantly share code, notes, and snippets.

@xinlc
Created January 18, 2018 03:08
Show Gist options
  • Save xinlc/e6d37b3085ef723d1a2aa869a718cbc8 to your computer and use it in GitHub Desktop.
Save xinlc/e6d37b3085ef723d1a2aa869a718cbc8 to your computer and use it in GitHub Desktop.
Turn a regular node function into one which returns a thunk
// ES5版本
var Thunk = function(fn){
return function (){
var args = Array.prototype.slice.call(arguments);
return function (callback){
args.push(callback);
return fn.apply(this, args);
}
};
};
/*
function f(a, cb) {
cb(a);
}
const ft = Thunk(f);
ft(1)(console.log) // 1
*/
// ES6版本
const Thunk = function(fn) {
return function (...args) {
return function (callback) {
return fn.call(this, ...args, callback);
}
};
};
// node-Thunkify
function thunkify(fn) {
return function() {
var args = new Array(arguments.length);
var ctx = this;
for (var i = 0; i < args.length; ++i) {
args[i] = arguments[i];
}
return function (done) {
var called;
args.push(function () {
if (called) return;
called = true;
done.apply(null, arguments);
});
try {
fn.apply(ctx, args);
} catch (err) {
done(err);
}
}
}
};
/*
function f(a, b, callback){
var sum = a + b;
callback(sum);
callback(sum);
}
var ft = thunkify(f);
var print = console.log.bind(console);
ft(1, 2)(print);
// 3
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment