I’ve been testing a bit with using $.Deferred() in jQuery lately and got a question. While deferred and promises are great for ajaxcalls that’s only intended to run once, I also got a form for adding new users that posts with ajax needs to be runnable multiple times. Now this crashes with the binary(ish) state of a deferred/promise as once they’re resolved or rejected it’ll keep that state. So my questions are:
-Can I use deferred for a task that will be called multiple times?
-If possible, is it recommended to use deferred for this or should I stick to the old method with just using the success/error callbacks of $.ajax?
Here some code I got together for posting the form, which works great once, but not multiple times.
var submittingUser = new $.Deferred();
var savingUser = submittingUser.pipe(function(data) {
return $.post('ajax.php', data);
});
$("#add_new_user").click(function() {
var data = $("#add_user_form").serialize();
submittingUser.resolve(data);
return false;
});
savingUser.then(function() {
//Success
}, function() {
//Failed
});
It makes no sense to use a deferred in that manner. A deferred represents an action; you cannot use it as an event emitter. You use a deferred when you start an asynchronous action, and want to do something when that action succeeds or fails.
$.post()returns a promise (actually it returns a jqXHR instance, which however implements the promise interface), so you can do$.post(...).fail(handleFailure).done(handleSuccess). But you cannot use a deferred to run some code every time something happens.