更新:此问题是 jQuery 1.7 与 1.8 的结果。永远不要在 1.7 中使用 Promise,因为它们无法通过在 .then
内返回 Promise 进行链接。 1.8 看起来他们并没有搞砸。
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();
预期:“我应该被调用”
实际:“我永远不应该被称为”
问题:我想要链接回调,并让其中任何一个都能够打破链接并触发 fail
函数,并跳过其他链接的回调。我不明白为什么所有的then都被触发而fail没有被触发。
我来自 NodeJS 的 Q 库,所以我首先尝试使用 .then
。但是,将其更改为 .pipe
没有任何效果。
最佳答案
您没有重新定义 promise
的值,请尝试以下操作:
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();
显然它确实按照您想象的方式工作,它只是没有记录 https://api.jquery.com/deferred.then 。很酷。这是 jQuery 1.8.0 中添加的新功能,很可能他们只是没有完成更新文档。
关于jquery - 尝试用 .then、.fail 和 .reject 打破 jQuery promise 链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12149993/