【问题标题】:How to force a Promise reject in a chain of promises in jQuery如何在 jQuery 的一系列承诺中强制拒绝承诺
【发布时间】:2020-07-05 20:40:51
【问题描述】:

在 jQuery 中,我们如何强制拒绝以停止流向所有后续 .then() 的流程?

$.post('myfile.php', function(data, textStatus, jqXHR) {
    // Do things
    // $.Deferred.reject(); How can we manually reject here?
}).then(function(data, textStatus, jqXHR) {
    alert('Then');
}).fail(function(jqXHR, textStatus, errorThrown) {
    alert('Failed');
});

在我上面的代码中,$.post() 成功,但是我希望你阻止代码转到下一个 .then()。

【问题讨论】:

    标签: javascript jquery promise


    【解决方案1】:

    $.post() 的第二个参数中的函数是回调函数,当 post 请求成功完成时调用。你不能将(在大多数情况下包括这个)回调函数与 Promise 结合起来。

    $.post('myfile.php', function(data, textStatus, jqXHR) {
        // this code in callback function will be executed if the request has been sent successfully
        //...
    }).then(function(data, textStatus, jqXHR) {
        // this code will be executed if the promise has been resolved, ie if the request has been sent successfully
        //...
    }).fail(function(jqXHR, textStatus, errorThrown) {
       // this code will be executed if the promise has been rejected, ie if the request HASN'T been sent successfully
       //...
    });
    

    所以回答你的问题 - 没有办法在回调函数中强制拒绝。

    但是,您可以停止使用回调函数并将其内容移动到那时。您的代码应如下所示:

    $.post('myfile.php').then(function (data, textStatus, jqXHR) {
        // Do things from callback function
    
        if (error_occured) {
            throw ("error"); //Force a rejection using throw
        }
    
        // this won't execute if error_occured but it will execute if it didn't
    }).catch(function (jqXHR, textStatus, errorThrown) {
        alert('Failed'); // post failed or error occured in then
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-25
      • 2017-10-25
      • 2017-09-04
      • 1970-01-01
      • 2013-09-16
      • 2019-04-09
      • 2017-03-12
      • 2015-08-26
      相关资源
      最近更新 更多