Created
July 7, 2010 07:30
-
-
Save mostlygeek/466425 to your computer and use it in GitHub Desktop.
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
/** | |
* Trying out different code approaches to break out of a | |
* deep callback chain in node.js | |
* | |
*/ | |
/** | |
* TEST #1 - Using a try/catch block | |
*/ | |
(function (throwError) { | |
var sys = require('sys'), | |
c = 0, | |
action = function (callback) { | |
c = c + 1; | |
sys.puts("Test 1, step: " + c); | |
callback(); | |
}; | |
// start the callback chain | |
try { | |
action(function () { | |
action(function () { | |
action(function () { | |
/* | |
this will stop the callback chain here. | |
however, if it is just an error and not an exception | |
perhaps using a custom error handler would be better | |
See below | |
*/ | |
if (throwError) { | |
throw new Error("BOOM"); | |
} | |
action(function () { | |
sys.puts("Finished! Test #1"); | |
}); | |
}); | |
}); | |
}); | |
} catch (err) { | |
sys.puts("Caught Exception: " + err.message); | |
} | |
}(false)); // toggle true/false to throw exception | |
/** | |
* TEST #2 - using a function error handler | |
*/ | |
(function (doError) { | |
var sys = require('sys'), | |
c = 0, | |
action = function(callback) { | |
c = c + 1; | |
sys.puts("Test 2, step: " + c); | |
callback(); | |
}, | |
errorHandler = function() { | |
sys.puts("In error hander!"); | |
}; | |
// Perform a callback chain | |
action(function () { | |
action(function () { | |
action(function () { | |
// Using a decision loop to break out of the chain | |
if (doError) { | |
errorHandler(); | |
return; | |
} else { | |
action(function() { | |
sys.puts("Finished! Test #2"); | |
}); | |
} | |
}); | |
}); | |
}); | |
}(false)); // toggle true/false to throw exception |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment