Is it possible to add methods to JQuery's promise object?

后端 未结 3 1174
萌比男神i
萌比男神i 2021-01-17 02:23

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         


        
相关标签:
3条回答
  • 2021-01-17 03:02

    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();
    
    0 讨论(0)
  • 2021-01-17 03:07

    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));
    
    0 讨论(0)
  • 2021-01-17 03:09

    Frankly, I wouldn't use jQuery "Promises" at all since they do not even follow the spec. Use the bluebird library, for example.

    0 讨论(0)
提交回复
热议问题