I have to call the functions in an order, but somehow they work independently.
Here are the functions:
function a(){
Ajax_Call_1();
}
function b(){
Ajax_Call_2();
}
function c(){
Ajax_Call_3();
}
$.when( a() ).then( $.when( b() ).then( c() ) );
When I run it, it looks like:
A works
C works
B works
But sometimes:
C works
A works
B works
How can I order them?
You can chain promise-like objects with using then
method. Note the difference between then
and done/fail
, a done callback passed to then
can return a new promise-like object for the rest of the control flow. This is why you can do the chaining. See the documentation.
a().then(b).then(c).done(function() { // the last promise has been resolved });
All of your functions should return
the promise object for this to work. So your b
should look like this.
function b(){
return Ajax_Call_2();
}
Where Ajax_Call
itself should return the ajax
call, like return $.ajax(...)
.
Note that as both b
and c
returns the promise, you can pass them directly to then
.