Skip to content

Instantly share code, notes, and snippets.

@dyoder
Created October 7, 2011 19:27
Show Gist options
  • Save dyoder/1271154 to your computer and use it in GitHub Desktop.
Save dyoder/1271154 to your computer and use it in GitHub Desktop.
Function and method callbacks for simplifying error handling
// So we start with a function that will allow to create new functions that
// convert errors into events.
var safeFactory = function(emitter) {
return function(fn) {
return function(err,value) {
if (err) { emitter.emit("error",err); }
else fn(value);
}
}
};
// Then you can do:
//
// var safe = safeFactory(this);
//
// ...
//
// asyncThing(safe(myCallback));
//
//
// Or (assuming you have a library like underscore):
//
// asyncThing(safe(_.bind(this,myCallback)));
//
// This opens the possibility of defining a function that defines a method
// that converts an async call into a safe invocation.
var safeMethodFactory = function(object,method,async,callback) {
return function() {
var args = _(arguments); // converts arguments to an Array
args.push(safe(_.bind(object,callback)));
return async(args);
}
};
//
// So now you could do something like this:
//
// var A = function() {
// this.readFile = safeMethodFactory(this,fs.readFile,this.parse);
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment