Waiting for AJAX to complete inside the $ .each loop

I can not get jQuery to disable work if called from a loop $.each.

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);
});
+3
source share
2 answers

The problem is to use when.

In particular, it is not in use apply- so it "waits" for $ and an array of pending (which will be "resolved" immediately), and not every pending one.

Compare with:

$.when.apply($, deferreds).done..
+3
source

It seemed to me that I am referring my answer here to a very similar thread regarding ajax calls within each loop.

OP, , , "" , , , ajax/ .

0

All Articles