0

I'm using jQuery to run some ajax:

var stuff = {};

function do_stuff(thing){
    stuff[thing.id] = thing;
}

function fun(){
    var calls = [];

    for(var i = 0; i < 10; i++){
        var call = $.get(URL, function(data){
             do_stuff(data);
        });
        calls.push(call);
    }

    $.when(calls).done(function(){
        console.log(stuff);
    });
}

I'm using $.when, but what I get is {} instead of the data that I expect. When I set a breakpoint in Chrome, the log line gets called before any of the do_stuff calls - so apparently the order of the calls get mixed up. Is there a way I can ensure the console.log(stuff) line gets called after my get callbacks do?

jfriend00
  • 683,504
  • 96
  • 985
  • 979
Wayne Werner
  • 49,299
  • 29
  • 200
  • 290

1 Answers1

0

You should read up on deferred objects: http://api.jquery.com/category/deferred-object/

You're correct in using $.when, but that accepts arguments of deferred objects. So in reality you need something like $.when(calls[0], calls[1], ...). This is kind of cumbersome, so luckily can use the javascript function .apply and get something like:

$.when.apply(null, calls).done(function() {
    console.log(stuff);
}
sahbeewah
  • 2,690
  • 1
  • 12
  • 18