Reputation: 7026
I am loading some data through a $.get
method. I have used the a success function in the get
call. But I'm also using a when
/then
construction.
Do both callbacks get called, and if so, which occurs first and why?
$.when(
$.get("test.html", functionA )
).then( functionB );
If successful, is this guaranteed to call functionA
, then functionB
? Or is there a situation where B might occur before A, or can something in functionA
ever prevent functionB
from being called? I couldn't find the answer in the jQuery docs.
Upvotes: 2
Views: 446
Reputation: 5729
Summary: The functionA
will be called earlier, than the functionB
in your example. The success
and error
callbacks from jQuery.ajax
settings (or passed to $.get
in your example) will be called earlier, than any callback attached to the returned jqxhr
object later. Well, today :-)
Details: Documentation of jQuery.ajax() does not mention this. You'd better avoid depending on it, if you can.
As long as you develop with a particular jQuery version, you can inspect its implementation and assume, that it doesn't change. If you upgrade, you should check, if the assumption is still valid.
For example, latest releases in all supported branches of jQuery (1.12.4, 2.2.4 and 3.1.1) register the success
and error
callbacks from jQuery.ajax settings before the caller gets the jqxhr
object and can register their callbacks. The jqxhr
object is a Deferred Object which guarantees, that handlers attached to its resolution or rejection are executed in the order of their attaching. You can confirm it in the documentation of deferred.done(), for example. It means, that, success
and error
callbacks from jQuery.ajax settings will be always called earlier, than any callback attached to the returned jqxhr
object later.
See jQuery.ajax 3.1.1 sources:
// Install callbacks on deferreds
completeDeferred.add( s.complete );
jqXHR.done( s.success );
jqXHR.fail( s.error );
I admit, that changing the order of execution is rather unlikely in future jQuery updates. That's why I think, that depending on it would be pretty stable.
Upvotes: 4