I have an $.ajax promise and want to check whether my (syntactically valid) response contains an error, triggering the rejected status in that case.
I have worked wi
Now updated for jQuery 1.8+
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
});