Use promises and $.when
:
$.when(ajaxCall1(), ajaxCall2()).then(ajaxCall3);
where ajaxCallX
is something like
function ajaxCall1() {
return $.ajax(...);
}
This basically means "after both, the promise of ajaxCall1
and the promise of ajaxCall2
are resolved, execute the function ajaxCall3
".
This works because the object returned by $.ajax
(and similar methods) implements the promise interface. More information can also be found in the $.ajax
documentation.
The responses of each Ajax call are passed to the then
callback as arguments. You can acess them as
$.when(ajaxCall1(), ajaxCall2()).then(function(a1, a2) {
// a1[0] is the response of the first call
// a2[0] is the response of the second call
ajaxCall3(a1[0], a2[0]);
});
Have a look at the $.when
documentation for another example.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…