Question

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?

Était-ce utile?

La solution

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
});

Autres conseils

Simplest thing is a counter and check:

var counter = 0;

$.ajax('....', function(data) {
    ... do your processing loop here
    counter++;
    if (counter >= 3) {
        do_the_post_counter_stuff();
    }
});

When each the ajax response handler finishes, it increments the counter and checks if it's past the limit. If it is past the limit, it just calls your "move onwards" function.

I just ran into a similar problem myself. I was running a series of ajax requests in a while loop. Some calls were not being made! It was killing me!! My conclusion was that my browser -- Google Chrome -- ignores "duplicate" requests.

Take a look at this pseudo code:

while (i < ajaxCallArray.length) {
    currentAjaxObject = ajaxCallArray[i];
    ajaxPost = $.post(currentAjaxObject.url, function(data) {
    //response data needs to go into a function such that each request gets its own "data" variable created.otherwise it just overwrites data!!
    processAjaxResponse(data, currentAjaxObject);
        },"json");
i++;
}

If ajaxCallArray[0].url = "http://www.google.com", ajaxCallArray[1].url = "http://www.google.com", and ajaxCallArray[2].url = "http://www.google.com" the browser will only actually make 1 call!!

The solution: You have to do something like ajaxCallArray[0].url = "http://www.google.com?count=0", ajaxCallArray[1].url = "http://www.google.com?count=0", and ajaxCallArray[2].url = "http://www.google.com?count=0" even if you dont use those url parameters, just put something to make them distinct. That way the browser will process all the calls, even if they are done instantly.

Hope this helps!!

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top