How to load multiple models sequentially in Ember JS route

时间秒杀一切 提交于 2019-12-12 19:53:08

问题


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:


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.



来源:https://stackoverflow.com/questions/21212951/how-to-load-multiple-models-sequentially-in-ember-js-route

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!