【问题标题】:How to change promise resolve result in chained .then() function如何在链式 .then() 函数中更改承诺解析结果
【发布时间】:2025-12-11 20:55:01
【问题描述】:

现在,我有一个被拒绝的承诺链:

dfd = $.Deferred();

dfd
    .then(function(){}, function(x) {
        return x + 1; // 2
    })
    .then(function(){}, function(x) {
        return x + 1; // 3
    })
    .then(function(){}, function(x) {
        log('reject ' + x); // 3
        return x + 1; // 4
    });

dfd.reject(1)

我想知道如何沿着 .then 链向下解决它(转向成功处理程序)?

谢谢

【问题讨论】:

    标签: jquery promise


    【解决方案1】:

    通过在任何需要的时间点返回一个已解决的承诺:

    dfd
        .then(function(){}, function(x) {
            return x + 1; // 2
        })
        .then(function(){}, function(x) {
            return $.Deferred().resolve(x + 1); // switch to success
        })
        .then(function(){}, function(x) {
            log('reject ' + x); // this will never happen now
        });
    

    docs 的相关部分是(强调我的)

    这些过滤器函数可以返回一个新值传递给 承诺的 .done().fail() 回调,或者他们可以返回 另一个将通过的可观察对象(Deferred、Promise 等) 它的已解决/拒绝状态和值到承诺的回调。

    【讨论】:

    • 值得注意的是,可以使用 $.when()$.when(value) 生成已解析的 jQuery 承诺,其中任何一个都可以从错误处理程序返回,以沿着成功路径发送承诺链。
    • 请注意,从 jQuery 的下一个版本开始,执行 return x + 1 也可以。
    • @BenjaminGruenbaum:我不知道。有什么地方可以让我了解更多信息吗?
    • @Jon 我最近写的关于它的参考文献是in this answer,但 jQuery 问题跟踪器也是阅读它的好地方。