Reputation: 1290
What exactly should I use for standalone asynchronous operations; deferred objects or is ajax done()
/fail()
enough? What is the difference?
I understand that deferred.when()
is useful as it allows us to know when all of multiple async operations are completed. But what about one async operation? done()
/fail()
allows me to know when it is completed too.
Upvotes: 0
Views: 664
Reputation: 22158
$.ajax()
method returns a $.Deferred()
object. So you are using deferreds in all cases. You can make your own deferred but ajax will return the same automatically. This is only with jQuery, vanilla javascript have not this functionality.
$.ajax()
will return the following promise methods:
fail()
, done()
, always()
and then()
.
What Jquery forum says:
The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise
Detailed reference to jQuery $.ajax
is available here, http://api.jquery.com/jQuery.ajax/
Upvotes: 4
Reputation: 356
From the Documentation:
jQuery.Deferred() introduces several enhancements to the way callbacks are managed and invoked. In particular, jQuery.Deferred() provides flexible ways to provide multiple callbacks, and these callbacks can be invoked regardless of whether the original callback dispatch has already occurred.
And:
One model for understanding Deferred is to think of it as a chain-aware function wrapper.
So like you said, the big difference is that the deferred.when
is useful when handling multiple requests. Answering your question, for standalone operations, done()
and fail()
will do just fine, and are easier to implement, in my opinion c:
Upvotes: 1