试图用.then,.fail和.reject打破jQuery Promise链 [英] attempting to break jQuery promise chain with .then, .fail and .reject
问题描述
更新:此问题是jQuery 1.7 vs 1.8的结果.切勿在1.7中使用promise,因为它们不能与在.then
中返回promise链接在一起. 1.8看起来他们并没有搞砸.
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 looks like they didn't mess it up.
http://jsfiddle.net/delvarworld/28TDM/
// make a promise
var deferred = $.Deferred();
promise = deferred.promise();
// return a promise, that after 1 second, is rejected
promise.then(function(){
var t = $.Deferred();
setTimeout(function() {
console.log('rejecting...');
t.reject();
}, 1000);
return t.promise();
});
// if that promise is successful, do this
promise.then(function() {
console.log('i should never be called');
})
// if it errors, do this
promise.fail(function() {
console.log('i should be called');
});
deferred.resolve();
预期:应该给我打电话"
Expected: 'i should be called'
实际:我永远都不会被呼唤"
Actual: 'i should never be called'
问题:我想链接回调,并使它们中的任何一个都能够断开链接并触发fail
函数,并跳过其他链接的回调.我不明白为什么会触发所有事件,而不会触发失败.
Problem: I want to chain callbacks and have any one of them be able to break the chain and trigger the fail
function, and skip the other chained callbacks. I don't understand why all of the thens are triggered and the fail is not triggered.
我来自NodeJS的Q库,因此我首先使用.then
进行了尝试.但是,将其更改为.pipe
无效.
I'm coming from NodeJS's Q library, so I tried it with .then
first. However, changing it to .pipe
has no effect.
推荐答案
您没有重新定义promise
的值,请尝试以下操作:
You aren't re-defining the value of promise
, try this:
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.
这篇关于试图用.then,.fail和.reject打破jQuery Promise链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!