简体   繁体   中英

$.ajax Deferred object

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: callback in 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 error callback. If I write:

function doAjax() {
    return $.get(...);
}

I can then attach arbitrary numbers of done and fail handlers to the result of that function call, without ever having to pass those handlers into the doAjax function.

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 using success:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM