简体   繁体   中英

How to force a Promise reject in a chain of promises in jQuery

In jQuery, how would we force a rejection to stop the flow to all following.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');
});

In my code above, $.post() succeeds, but then I'd like you stop the code from going to the next.then().

The function in second argument of $.post() is callback function which is called when post request is succesfully compleetd. You can't combine (in most cases including this one) callback functions with promises.

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

So to answer your question - there's no way to force a rejection inside callback function.

However, you can stop using the callback function and move its contents to then. Your code should look something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM