5

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);
});
Charlie
  • 11,380
  • 19
  • 83
  • 138
matthoiland
  • 912
  • 11
  • 24

2 Answers2

3

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..
user2864740
  • 60,010
  • 15
  • 145
  • 220
0

I thought I would link to my answer here on a very similar thread regarding ajax calls within an each loop.

Unlike the OP's code, this method is a little more complex showing how to await the 'successes' back up through a couple of function calls and I think would be useful for many people encountering the ajax/each issue.

Community
  • 1
  • 1
Cameron Forward
  • 702
  • 8
  • 16