This is actually a perfect place to use promises. All the jQuery Ajax calls return promises by default which means you can simply chain them together:
$.ajax({/*snip*/}).then(
function(result){
doSomethingWithResult(result);
return $.ajax({/*snip*/});
}).then(function(result){
doSomeFinalProcessing(result);
});
And of course, a jsFiddle to demonstrate this happening.
Here is an updated fiddle that shows how to combine multiple simultaneous promises and combine their results.
http://jsfiddle.net/jwcarroll/U3N9u/
And the code:
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
function doStuffLater(msg){
var def = $.Deferred();
setTimeout(function(){
def.resolve(msg);
}, getRandomInt(300, 1000));
return def.promise();
}
function needsBothReturns(one, two){
console.log({one:one, two:two});
}
var first = doStuffLater("Sent First");
var second = doStuffLater("Sent Second");
$.when(first, second).done(function(result1, result2){
needsBothReturns(result1, result2);
});
startOtherAsync?startOtherAsyncwill pass nothing. but thesuccessof his ajax call will call backhandleCompletionpassing the returned ajax value.