簡體   English   中英

如何在 jQuery 的一系列承諾中強制拒絕 Promise

[英]How to force a Promise reject in a chain of promises in jQuery

在 jQuery 中,我們如何強制拒絕以停止流向所有 follow.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() 成功了,但是我希望你阻止代碼轉到 next.then()。

$.post()的第二個參數中的 function 是回調 function,當 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
   //...
});

所以回答你的問題 - 沒有辦法在回調 function 中強制拒絕。

但是,您可以停止使用回調 function 並將其內容移至 then。 您的代碼應如下所示:

$.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
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM