Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waiting until AJAX completes inside an $.each loop

I can't seem to get jQuery deferrers to work if they are called from an $.each loop.

var deferreds = [],
    ids = ['1234', '4321'],
    users = [];

$.each(ids, function(i,v){
    deferreds.push(
        $.getJSON('api/users/'+v, function(i,v){
            users.push(v.username);
        })
    );
});

$.when($, deferreds).done(function(){
    console.log(users);
});
like image 371
matthoiland Avatar asked Oct 20 '22 15:10

matthoiland


1 Answers

The problem is the use of when.

In particular, the usage is missing an apply - so it is "waiting on" $ and the deferreds array (which will "resolve" immediately), not each deferred.

Compare with:

$.when.apply($, deferreds).done..
like image 71
user2864740 Avatar answered Dec 01 '22 19:12

user2864740