Skip to content

Instantly share code, notes, and snippets.

@marclar
Last active December 18, 2015 11:38
Show Gist options
  • Save marclar/5776627 to your computer and use it in GitHub Desktop.
Save marclar/5776627 to your computer and use it in GitHub Desktop.
A useful function for handling node-style callbacks.
//Add "ifok" function
global.ifok = function(args, msg, cb){
var me = this;
args = Array.prototype.slice.call(args);
var err = args.shift();
var log = (me.log || console.log);
//You can comment out a log message by adding a space at the beginning
if(msg.length && msg.charAt(0) === ' '){
msg = null;
}
else{
msg = (err ? '#err: ' : '#ok: ') + msg;
}
if(msg){
log.call(me, msg);
if(err){
log.call(me, err);
}
}
//Delay the callback until after returning the "me" object
process.nextTick(function(){
cb.apply(me, args);
});
//Return
return me;
};
@marclar
Copy link
Author

marclar commented Jun 13, 2013

I use this to simplify callbacks that have an error as the first parameter (as is node convention).

usage:

db.collection.find({}, function(err, cursor){
    var me = ifok(arguments, 'Continue doing something...', function(cursor){

        // You'll only get to this point if there wasn't an error. 
        // If there was an error, you'll see:
        //   
        //     "#err: Continue doing something..."
        //   
        // In addition, the original "this" object is stored in the "me" variable.

    });
});

Hope this is useful!

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