Reputation: 2485
What I want to achieve is the PopUpView only gets called-once all the Models have been saved.
When running the code, the popup view runs before the saves have completed.
var promises = []
_.each(exampleModels, _.bind(function (resource) {
var filter = this.resources.get(resource.id);
filter.fetch(
{
success: function (model, response) {
var participant = new Model({
example: "text"
});
promises.push(participant.save());
}
});
}, this));
$.when.apply($, promises).then(_.bind(function () {
var popupForm = new PopUpView({
});
this.$el.append(popupForm.$el);
}, this));
Upvotes: 1
Views: 69
Reputation: 33344
model.fetch
and model.save
then
return a new promise1You could build your array of promises like this
var promises = _(ids).chain()
.map(function(id) {
// get the models you want
return c.get(id);
})
.map(function(model) { // build a promise for each model
return model.fetch(). // promise returned by fetch
then(function(resp) {
var participant = new M({
example: "text"
});
return participant.save(); // promise returned by save
});
})
.value();
$.when.apply($, promises).then(function() {
console.log('done');
});
And a demo http://jsfiddle.net/nikoshr/du44m1ha/
1 Since jQuery 1.8
Upvotes: 1
Reputation: 15104
The problem is that fetch
is asynchronous too. So when you hit the line $.when.apply(...
, promises
is an empty array. So the promise returned by when
trigger the then
directly.
Upvotes: 1