I've written a plugin that is supposed to fetch error messages from an API and display them inside an element's HTML. I want to implement it as a promise, so that other events can be chained to it via a done
or always
callback. The simplified version of the plugin looks like this:
(function( $ ) {
$.fn.flashAlerts = function() {
var deferred = $.Deferred();
var field = $(this);
$.getJSON( "alerts", {})
.done(function( data ) {
// Display alerts
field.html(data['message']);
deferred.resolve();
});
return deferred.promise();
};
}( jQuery ));
And a use scenario might look like this:
$("#myForm").submit(function(e) {
e.preventDefault();
var form = $(this);
// Disable submit button
form.disableSubmitButton();
var serializedData = form.serialize();
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: serializedData
}).fail(function(jqXHR) {
// Display errors on failure
$('#alerts').flashAlerts().done(function() {
// Re-enable submit button
form.enableSubmitButton();
});
});
});
The idea is to enforce the following sequence of actions:
- POST the form. Before the request, disable the submit button. When the request is complete,
- GET the errors from the
alerts
api. Once that request is complete, display the error messages. After the error messages have been displayed, - Re-enable the submit button.
This code seems to work as it stands, but I have no idea if the deferrals are working in the correct order (or if I'm just getting lucky with the timing of the requests).
So, am I doing this correctly? How could I test that the deferral order is as desired?