2

What is the best way to load multiple models sequentially in Ember JS?

e.g.

App.ProductRoute = Ember.Route.extend({
   model: function(params) {
     // first call
     this.store.find('Product');
     // second call should only be called after the first find is completed    
     var prod = this.store.find('Product', params.product_id);
     // third call should only be called after the above is completed
     this.store.find('ProductOptions', prod.get('optionId');
     return ??? 
   },
   setupController: function(controller, model){
      // how would one the set up the controllers?
   }
});

This post shows how to load multiple models in a route at the same time.

1 Answer 1

3

You can create your own promise, and resolve a hash. That will be the model in the controller, no need to override setupController unless you want them stored on the controller somewhere different.

App.ProductRoute = Ember.Route.extend({
   model: function(params) {
     var self = this;
     return new Em.RSVP.Promise(function(resolve, reject){
       // first call
       self.store.find('Product').then(function(products){

         // second call should only be called after the first find is completed    
         self.store.find('Product', params.product_id).then(function(product){
           // third call should only be called after the above is completed
           self.store.find('ProductOptions', product.get('optionId').then(function(productOption){
             resolve({
               products:products,
               product:product,
               productOptions:productOptions
               }); 
           });
         });
       });
     }); 
   }
});

BTW, it sounds like product options should be an async relationship on the product.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you kingpin2k - you are awesome!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.