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