Skip to content

Instantly share code, notes, and snippets.

@huttj
Created June 16, 2015 05:21
Show Gist options
  • Save huttj/e012aa95886c7b4aff8c to your computer and use it in GitHub Desktop.
Save huttj/e012aa95886c7b4aff8c to your computer and use it in GitHub Desktop.
A promise that catches itself if no one else does.
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