jQuery execute after 3 AJAX calls and loops are done

Mark picture Mark · Aug 16, 2013 · Viewed 7.8k times · Source
var request3 = 
window.SendAjax(window.siteRoot + "Home/GetTweets", "{}", function(msg) {
    //tweet
    $.each(msg, function(i, value) {
       ...

    });
    console.log("loop done");
});


$.when(request1, request3).then(function () {
  console.log(feedItems);
});

I'm trying to use the $.when() jQuery method. I have 3 AJAX methods that get data then perform a loop with the data. The $.when is executing when that AJAX async is done, I need it to wait until the loops are done. I didn't show ALL the code, but there are 3 AJAX calls that fetch data then do loops. When all 3 are done, THEN do something. Thoughts?

Answer

Jason P picture Jason P · Aug 16, 2013

I assume SendAjax() looks like this:

function SendAjax(url, data, callback) {
    return $.ajax({
        ...
        success: callback,
        ...
    });
}

If so, change it to something like this:

function SendAjax(url, data, callback) {
    var def = $.Deferred();
    return $.ajax({
        ...
        success: function() {
            callback();
            def.resolve();
        },
        ...
    });
    return def.promise();
}

Then you can do this:

var ajax1 = SendAjax(...);
var ajax2 = SendAjax(...);
var ajax3 = SendAjax(...);

$.when(ajax1, ajax2, ajax3).done(function() {
    //do stuff
});