I'm trying to use a custom deferred object to manage some callbacks. I've figured out the easy case:
var deferred = $.Deferred();
deferred.done(function() {
console.log( 'done' );
});
var json = $.getJSON('/foo');
json.then(
function() {
deferred.resolveWith(this, arguments);
}
);
But I need to inspect the response before resolving/rejecting. I'd like to add something like this:
deferred.pipe(
function(response) {
if (response.message === 'error') {
return $.Deferred.reject(response);
}
return response;
}
);
But when I do, my original done()
callback is always called regardless. I'm pretty sure it's because once I call deferred.resolveWith()
it's too late to "roll back" and mark it as rejected later. I know I could just move the conditional up into the first argument to json.then()
, but that seems to miss the point of a deferred object -- I thought they were meant for encapsulating all of these behaviors into a single place.
Is it possible to put both the conditional and the callback into deferred
while still resolving it elsewhere?