jquery - 尝试用 .then、.fail 和 .reject 打破 jQuery promise 链

标签 jquery deferred chain promise

更新:此问题是 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 的值,请尝试以下操作:

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();

显然它确实按照您想象的方式工作,它只是没有记录 https://api.jquery.com/deferred.then 。很酷。这是 jQuery 1.8.0 中添加的新功能,很可能他们只是没有完成更新文档。

关于jquery - 尝试用 .then、.fail 和 .reject 打破 jQuery promise 链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12149993/

相关文章:

go - 我可以创建一个只能与 defer 一起使用的函数吗?

javascript - 我应该返回 deferred.resolve/reject 的结果吗?

javascript - 如何存储功能链的数据?

java - Struts 2 - 当第二个操作与表单一起使用时,在操作之间传递参数会丢失

javascript - True 和 False 循环数组

javascript - 在元素上具有不同动画的 jQuery 幻灯片

javascript - 用jQuery模拟复选框悬停效果

java - 有没有办法使用 GWT.create(...) 实例化泛型类型的类?

python从tsv文件链接一个列表

php - 使用 jquery ajax 发布关联数组