Created
June 16, 2015 05:21
-
-
Save huttj/e012aa95886c7b4aff8c to your computer and use it in GitHub Desktop.
A promise that catches itself if no one else does.
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
var $q = require('q'); | |
function catchIfNeeded(name) { | |
var caught = false; | |
var promise = $q.try(function() { | |
throw new Error('Catch me!'); | |
}).catch(function(err) { | |
// This function is executed on the next "tick" of the event loop | |
if (caught) { | |
throw err; | |
} else { | |
console.log((name || 'You') + ' didn\'t catch me... T_T'); | |
} | |
}); | |
var _then = promise.then; | |
promise.catch = function(rejected) { | |
if (rejected && typeof rejected === 'function') { | |
caught = true; | |
console.log((name || 'You') + ' caught me!'); | |
} | |
_then.call(promise, void 0, rejected); | |
} | |
promise.then = function(fulfilled, rejected, progressed) { | |
if (rejected && typeof rejected === 'function') { | |
caught = true; | |
console.log((name || 'You') + ' caught me!'); | |
} | |
_then.call(promise, fulfilled, rejected, progressed); | |
} | |
return promise; | |
} | |
catchIfNeeded(1); // 1 didn't catch me... T_T | |
catchIfNeeded(2).catch(function(){}); // 2 caught me! | |
catchIfNeeded(3).then(function(){}); // 3 didn't catch me... T_T | |
catchIfNeeded(4).then(function(){}, function(){}); // 4 caught me! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment