Last active
December 18, 2015 11:38
-
-
Save marclar/5776627 to your computer and use it in GitHub Desktop.
A useful function for handling node-style callbacks.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I use this to simplify callbacks that have an error as the first parameter (as is node convention).
usage:
Hope this is useful!