These two codes (1)(2) seems to work in the same manner to me.
My questions are:
1) Are these two codes equivalent?
2) If yes why? If not what should I prefer and why?
(1)
$.ajax({
url: backendRouter.generate('feedback_send'),
type: 'POST',
dataType: 'json',
data: data
success: callback,
done: function () {
// some code
}
});
(2)
$.ajax({
url: backendRouter.generate('feedback_send'),
type: 'POST',
dataType: 'json',
data: data
success: callback
}).done(function () {
// some code
});
Yes, the two codes are equivalent, except that (by mistake?) you’ve left
success: callbackin the latter.However IMHO the latter is preferred as deferred objects are far more flexible than supplying a callback directly to
$.ajax.In particular, using deferred objects allows for much better separation of logic and responsibility between initiating the AJAX call and the processing of the results of that call. Also, some of the AJAX helper functions don’t support an
errorcallback. If I write:I can then attach arbitrary numbers of
doneandfailhandlers to the result of that function call, without ever having to pass those handlers into thedoAjaxfunction.I can also combine the returned
promise()object with other promises using$.when(),$.pipe(), etc, for very powerful synchronisation between multiple asynchronous events (including other AJAX calls, timers, animations, etc). I can’t do that usingsuccess: