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.
Summary: The
functionA
will be called earlier, than thefunctionB
in your example. Thesuccess
anderror
callbacks fromjQuery.ajax
settings (or passed to$.get
in your example) will be called earlier, than any callback attached to the returnedjqxhr
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
anderror
callbacks from jQuery.ajax settings before the caller gets thejqxhr
object and can register their callbacks. Thejqxhr
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
anderror
callbacks from jQuery.ajax settings will be always called earlier, than any callback attached to the returnedjqxhr
object later.See jQuery.ajax 3.1.1 sources:
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.