admin管理员组

文章数量:1291014

I have the following function:

$.each(friends, function(friend, data) {
        var group = "Chat";

$.ajax({'type':'GET', 'url':'/site/getgroup?username=' + friend,
'success':function(callback){

group = callback;
self.addFriend(friend, data.status, group);

}, //ajax success
});  //ajax

            });

After these codes, I have some codes to initialize the chatBar using the Data from these .each and .ajax. However, right now since Ajax is async, it bees very buggy. How can I know that these .each are all finished with the returned ajax value without setting ajax async to false? (Means this part is pletely finished).

Like is there a way I can use .promise, plete, or XHRs to know the whole .each thing is plete? I tried out lots of stuff but they seem not to work for me.

Thank you,

I have the following function:

$.each(friends, function(friend, data) {
        var group = "Chat";

$.ajax({'type':'GET', 'url':'/site/getgroup?username=' + friend,
'success':function(callback){

group = callback;
self.addFriend(friend, data.status, group);

}, //ajax success
});  //ajax

            });

After these codes, I have some codes to initialize the chatBar using the Data from these .each and .ajax. However, right now since Ajax is async, it bees very buggy. How can I know that these .each are all finished with the returned ajax value without setting ajax async to false? (Means this part is pletely finished).

Like is there a way I can use .promise, .plete, or XHRs to know the whole .each thing is plete? I tried out lots of stuff but they seem not to work for me.

Thank you,

Share Improve this question asked Sep 20, 2013 at 15:17 jackhaojackhao 3,8574 gold badges23 silver badges44 bronze badges 1
  • I would approach that in a different way by making one Ajax request only and loop through the results in the callback. Although that solution might require some refactoring of getgroup. – Mina Commented Sep 20, 2013 at 15:33
Add a ment  | 

3 Answers 3

Reset to default 12

Use $.when()

var xhrs = []
$.each(friends, function (friend, data) {
    var group = "Chat";
    var xhr = $.ajax({
        'type': 'GET',
        'url': '/site/getgroup?username=' + friend,
        'success': function (callback) {
            group = callback;
            self.addFriend(friend, data.status, group);    
        }, //ajax success
    }); //ajax
    xhrs.push(xhr)
});

$.when.apply($, xhrs).done(function(){
    //all are plete
});

A simple solution is to have a status array and for each ajax request, on success/error handler to update & check the status array to see if all other ajax requests have finished. This way, you can store also the response for each ajax request.

Take a look at $.when() as it looks like it might solve your problem. I can't say for sure what it will do to $.each.

http://api.jquery./jQuery.when/

本文标签: javascriptJquery ajax inside each How to trigger function when the whole each is completeStack Overflow