1

I'm trying to save several backbone models (not in a collection) and execute code after they all get saved.

This is my code simplified:

var requestsArray = modelsArray.map(function(model) {
    return model.save();
});

$.when.apply(undefined, requestsArray)
    .done(function() {
        console.log('DONE CALLBACK');
        console.log('ARGS', arguments);
     })
    .fail(function() {
        console.log('FAILED');
        console.log('ARGS', arguments);
    });

But when I run this - the done callback gets fired immediately and it doesn't wait for the ajax requests to finish.

Why is that?

pesho hristov
  • 1,946
  • 1
  • 25
  • 43

1 Answers1

1

It doesn't happen directly with requests :(

I had to do it this way:

var deferredsArray = modelsArray.map(function(model) {
    var dfd = new $.Deferred();
    model.save().then(function() {
          dfd.resolve();
        }, function() {
          dfd.reject();
        });
    return dfd;
});

$.when.apply(undefined, deferredsArray)
    .done(function() {
        console.log('ALL SUCCESSFUL');
    })
    .fail(function() {
        console.log('AT LEAST ONE FAILED');
    });

And when when all are successful - then the done method of $.when gets called.

pesho hristov
  • 1,946
  • 1
  • 25
  • 43