10

i have two javascript functions, save() and saveAll(), set up as below:

function save(data) {
    return $.post('/save', data);
}

function saveAll(callback) {
    var dataArray = [];
    $.each(dataArray, function() {
        save(this);
    });
    callback();
}

i'm interested in modifying saveAll() so that it leverages jquery deferred objects, and raises the callback function once all save() operations have completed. however, i'm unsure of the exact syntax... specifically with relation to the $.each() inside of the $.when(). would it be something like this?

function saveAll(callback) {
    var dataArray = [];
    $.when(
        $.each(dataArray, function() {
            return save(this);
        })
    ).then(callback);
}
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
Omer Bokhari
  • 57,458
  • 12
  • 44
  • 58

3 Answers3

21

as Eli pointed out, $.when() accepts a comma separated list of arguments and not an array. using Function.apply() to pass in the array seems to do the trick.

function saveAll(callback) {
    var dataArray = [], deferreds = [];
    $.each(dataArray, function() {
        deferreds.push( save() );
    });

    $.when.apply(window, deferreds).then(callback);
}
Omer Bokhari
  • 57,458
  • 12
  • 44
  • 58
  • 2
    This is fantastic, was looking for just this. I'm suprised jQuery doesn't allow for an array of deferred objects natively. – Gary Green May 18 '11 at 11:11
  • 11
    Just be careful, because a little known fact about $.when is that it will immediately resolve if any one of the arguments is rejected/failed, without waiting for the rest! It's true :) And unexpected, if you ask me. I wrote a $.whenAll() that always waits for all the arguments to resolve, regardless of success/fail status: http://jsfiddle.net/InfinitiesLoop/yQsYK/ – InfinitiesLoop Oct 24 '11 at 20:44
1

You should be able to pass a comma-separated list of deferred objects to $.when and .then will execute once they all have resolved.

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

Eli
  • 17,397
  • 4
  • 36
  • 49
1

The problem I think is that $.each is returning your dataArray, not a list of Deferred objects like you want to feed to $.when.

entropo
  • 2,481
  • 15
  • 15