Skip to content

Instantly share code, notes, and snippets.

@fernandezpablo85
Created May 4, 2011 15:32
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save fernandezpablo85/955421 to your computer and use it in GitHub Desktop.
Save fernandezpablo85/955421 to your computer and use it in GitHub Desktop.
Explanation of the curry function for node.js
function curriedReadFile(path) {
var _done, _error, _result;
var callback = function(error, result) {
_done = true,
_error = error,
_result = result;
};
fs.readFile(path, function(e, r) {
callback(e, r);
});
// Here '_' is the function we pass to curriedReadFile
// Where we actually do the IO stuff
return function(_) {
// If fs.readFile returned (_done is set), we just execute our IO code with the results
if (_done) {
_(_error, _result);
// If it still hasn't return, our function that does IO stuff ('_')
// now becomes the callback (see fs.readFile body)
} else {
callback = _;
};
}
@fengmk2
Copy link

fengmk2 commented May 10, 2011

!! This is so cool

var fn = curriedReadFile('test.txt');
fn(function(err, data) {
  console.log(err, data);
});

@fernandezpablo85
Copy link
Author

Thanks!

Note that this is a friendlier version of the function described here:

http://bjouhier.wordpress.com/2011/04/04/currying-the-callback-or-the-essence-of-futures/

I haven't invented this, just made it a bit more readable (at least to my taste)

Cheers

@hansifer
Copy link

Is there a reason for wrapping callback(e, r)?

Ie, why not simply:

fs.readFile(path, callback);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment