Stop a Deferred callback queue in progress?
This dilemma may only exist because I'm an amateur and haven't thought of a better way. I love love love the new Deferred object, but I still can't use $.when() most of the time. The problem is that there are two kinds of errors: HTTP errors where an AJAX request fails, and application errors where the server-side code has a problem (like an empty form field). It requires logic like this pseudo-code:
- if (http_error)
- { handle the error }
- else
- {
- if (application_error)
- { handle the error }
- else
- { do what you actually wanted }
- }
A Deferred can't do this on its own, because it only knows about HTTP errors. The same callbacks happen whether there's an application error or not.
To handle potential application errors, I do the following over and over:
- var deferred = $.Deferred().done( stuff_to_do ).fail( handle_application_error );
- $.post( url, params, function(data) { special_error_check(data, deferred) }, 'json');
The special_error_check() sees if the JSON data contains error messages. If so, it calls deferred.reject(). If there are no errors, it calls deferred.resolve().
This works, but it would be simpler if a Deferred callback could stop remaining callbacks from running (like by returning false). You would first call the handle_application_error function. If no errors are found, callbacks continue. If errors are found, cancel the remaining callbacks. You would get nice simple syntax:
- $.when( $.post(url, params) ).done( handle_application_error, stuff_to_do ).fail( show_generic_error );
Wouldn't this be a better way of handling this situation?