Search code examples
jqueryember.jsember-datapromisedeferred

How to use jquery.when with ember data promises


I'm trying to fire a callback when multiple ember models have finished their save methods.

var promises = [];
modellist.forEach(function(mymodel){
    promises.push(mymodel.save())
}
$.when.apply(null, promises).done(function () {
    console.log('finished promises');
}
console.log('finished method');

The apply function is executed immediately.

Question: Which of the following is true?

  • promise != ember-promise
  • promise != deferred
  • ember-promise != deferred

Solution

  • I'm a big fan of RSVP.hash as it allows an object, while RSVP.all uses an array.

    If you want to use it in regular code to save multiple models.

    actions: {
       doSomething() {
         Ember.RSVP.hash({
           model1Saved: this.get('model1').save(),
           model2Saved: this.get('model2').save(),
        }).then((hash) => { 
          /* hash.model1Saved and hash.model2Saved are available here */ 
        }, (error) => { 
         /* Deal with error */ 
        });
       }
    } 
    

    Which is nice, because you don't have to mess with array indexes.

    Also when returning a model for the route

    model() {
    return Ember.RSVP.hash({
      posts: this.store.findAll('post'),
      tags: this.store.findAll('tag'),
      categories: this.store.findAll('category'),
    });
    },
    

    And then in the setupController method you can:

    setupController(controller, model) {
      this._super(controller, model.posts);
      controller.set('tags', model.tags);
      controller.set('category', model.categories);
    }