Last active
August 29, 2015 14:03
-
-
Save shimondoodkin/a6762d8ab29ea497e245 to your computer and use it in GitHub Desktop.
javascript callback guard - prevents a callback to be called twice
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
// cbguard by Shimon Doodkin - license: public domain | |
function cbguard(cb,printerr){ //kind of filter for callbacks. it prevents a callback to be called twice | |
var cb1=cb; | |
return function() { | |
if(cb1) { var cb2=cb1; cb1=false; return cb2.apply(this,arguments); } | |
else if(printerr)console.log(new Error('cb called twice').stack); | |
} | |
} | |
// usage example: | |
//function myfunction(cb) | |
//{ | |
// cb=cbguard(cb); // usage example | |
// // or | |
// // cb=cbguard(cb,true); // good when developing, it will protect and also tell you you have a problem, here a callback is called twice here. | |
// | |
// things that are based on event emitteres are usually have problems with multiple callbacks. | |
//i used it in a project https://github.com/shimondoodkin/bitcoin-ticker/blob/master/index.js#L46 | |
// in case of callback errors it is possible to trace the error using https://github.com/mattinsler/longjohn | |
// and writing console.log(new Error('callback trace').stack); in the callback to print from where it was called. | |
// example: | |
rates={ | |
dollar:["USDILS=X",0,"1/1/2000","0:00pm"], | |
} | |
var rest = require('restler'); | |
function update_dollar(cb) | |
{ | |
cb=cbguard(cb); // usage example | |
try | |
{ | |
rest.get('http://download.finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s=USDILS=X') | |
.on('complete', function(data) { | |
if(data instanceof Error) | |
{ | |
console.log(data.stack); | |
return cb(); | |
} | |
try | |
{ | |
data=JSON.parse("["+data.trim().replace(/""/,"\\\"")+']'); | |
} | |
catch(e) | |
{ | |
console.log(e.stack) | |
} | |
if(typeof data=='object' && data!==null) | |
rates.dollar=data; | |
cb(); | |
}); | |
} | |
catch(e) | |
{ | |
console.log(e.stack);cb(); | |
} | |
} | |
// |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment