[英]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.