在 jQuery 的 Deferred 对象中抛出错误 [英] Throwing an Error in jQuery's Deferred object
问题描述
我有一个 $.ajax
承诺并且想要检查我的(语法上有效的)响应是否包含错误,在这种情况下触发拒绝状态.
I have an $.ajax
promise and want to check whether my (syntactically valid) response contains an error, triggering the rejected status in that case.
我使用了自己的 Promise 库,可以轻松处理此类任务.我不太喜欢 jQuery 的 Promise (cache) 实现及其 Deferred
object 并且可能忽略了一些东西,因为我很少使用它.我认为要走的路只是使用 .then()
,这似乎相当复杂:
I have worked with my own promise library which deals such tasks easily. I do not really like jQuery's Promise (cache) implementation with its Deferred
object and may have overlooked something, because I seldom use it. I think the way to go is just using .then()
, which seems to be rather complicated:
return $.ajax(...).then(function success(response) {
var problem = hasError(response);
if (problem) {
var error = new $.Deferred;
error.reject(problem);
return error;
} else
return response;
});
这应该返回一个承诺,在出现网络错误或响应问题时被拒绝.但是返回一个被拒绝的 deferred 真的是 [only|best|shortest] 方法吗?
This should return a promise which is rejected in case of network errors or problems with the response. But is returning a rejected deferred really the [only|best|shortest] way to go?
我也会在 ajax 选项本身中提供有关如何处理此类错误抛出响应处理程序"的帮助,我找不到关于它们的良好文档.
I also would appriciate help on how to deal with such "error-throwing response handlers" in the ajax options themselfes, I could not find good documentation about them.
免责声明:不,我无法更改服务器响应.问题检测方法是同步的.我不想使用其他库,我对 jQuery 解决这个问题的方式特别感兴趣.
Disclaimer: No, I cant change the server responses. The problem-detecting method is synchronous. I don't want to use other libraries, I'm particularly interested in the way jQuery solves this.
推荐答案
现已针对 jQuery 1.8+ 进行更新
解决这个问题的最简单方法是运行 $.ajax
到 .then
的响应,以根据数据的成功或失败进行过滤.
The easiest way to tackle this is to run the response of $.ajax
through .then
to filter based on success or failure of the data.
$.ajax()
.then(function (response) {
return $.Deferred(function (deferred) {
var problem = hasError(response);
if (problem) {
return deferred.reject(problem)
}
deferred.resolve(response);
}).promise();
});
然后,您可以将这个新承诺返回给任何调用代码将使用它:
You could then return this new promise to whatever calling code would consume this:
var request = function () {
return $.ajax()
.then(function (response) {
return $.Deferred(function (deferred) {
var problem = hasError(response);
if (problem) {
return deferred.reject(problem)
}
deferred.resolve(response);
}).promise();
});
};
request()
.done(function (response) {
// handle success
})
.fail(function (problem) {
// handle failure
});
这篇关于在 jQuery 的 Deferred 对象中抛出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!