Forked from briancavalier/messy-async-with-callbacks.js
Created
January 30, 2016 11:33
-
-
Save illucent/9d485f718acdfb9468ef to your computer and use it in GitHub Desktop.
Messy async handling of error conditions
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
| function thisMightFail(callback, errback) { | |
| xhrGet('/result', callback, errback); | |
| } | |
| function recoverFromFailure(callback, errback) { | |
| recoverAsync( | |
| function(result) { | |
| if(callback) { | |
| try { | |
| callback(result); | |
| } catch(e) { | |
| // Ok, callback threw an exception, let's switch to errback | |
| // At least this will let the caller know that something went wrong. | |
| // But now, both the callback and errback will have been called, and | |
| // and the developer may not have accounted for that! | |
| errback(e); | |
| } | |
| } | |
| } | |
| function(error) { | |
| if(errback) { | |
| try { | |
| errback(error); | |
| } catch(ohnoes) { | |
| // What do we do now?!? | |
| // We could re-throw or not catch at all, but no one can catch | |
| // the exception because this is all asynchronous. | |
| // And now console.error has infiltrated deep into our code, too! | |
| console.error(ohnoes); | |
| } | |
| } | |
| }, | |
| ); | |
| } | |
| function getTheResult(callback, errback) { | |
| // Simulating the catch-and-recover behavior of try/catch | |
| thisMightFail(callback, function(e) { | |
| recoverFromFailure(callback, errback); | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment