attempting to break jQuery promise chain with .then, .fail and .reject

后端 未结 2 581
南旧
南旧 2021-02-05 20:20

Update: this issue was a result of jQuery 1.7 vs 1.8. Do not ever use promises in 1.7 beacuse they aren\'t chainable with returning a promise inside a .then. 1.8 lo

2条回答
  •  爱一瞬间的悲伤
    2021-02-05 21:21

    You aren't re-defining the value of promise, try this:

    http://jsfiddle.net/28TDM/1/

    var deferred = $.Deferred();
    promise = deferred.promise();
    
    promise = promise.then(function(){
        var t = $.Deferred();
        setTimeout(function() {
            console.log('rejecting...');
            t.reject();
        }, 1000);
    
        return t.promise();
    });
    
    promise.then(function() {
        console.log('i should never be called');
    })
    
    promise.fail(function() {
        console.log('i should be called');
    });
    
    deferred.resolve();
    

    Apparently it does work the way you thought it did, it just isn't documented https://api.jquery.com/deferred.then. Very cool. This is new functionality added in jQuery 1.8.0, more than likely they just aren't done updating the documentation.

提交回复
热议问题