I want to add a catch
method to JQuery\'s promise
object so I don\'t have to type the following every time:
.then(null,function(dat
You can create your custom then
$.Deferred().prototype.customthen = function(){
$.Deferred().prototype.then.call(this, null, ,function(data){
// handle error
return $.Deferred().resolve().promise();
})
}
You have added a new function named customthen to the prototype. So, this new function is available in all instances.
Now, you can use it as follows
.customthen();
Yes, it is possible, but I would strongly recommend not to do this. Rather use a proper promise library and assimilate your jQuery promises; so that you can use the libraries builtin (and correct) .catch()
method - so that you can omit that return $.Deferred().resolve().promise();
line as well.
The problem with extending jQuery promises is that they don't inherit from a prototype which we could simply amend, but use a factory pattern (read the source). You'll need to decorate it:
jQuery.Deferred = (function($Deferred) {
var Deferred = function(func) {
var deferred = $Deferred(func),
promise = deferred.promise();
deferred.catch = promise.catch = function(fnFail) {
return promise.then(null, fnFail);
};
return deferred;
};
return Deferred;
}(jQuery.Deferred));
Frankly, I wouldn't use jQuery "Promises" at all since they do not even follow the spec. Use the bluebird library, for example.