Building Model object from multiple rest calls

266 views Asked by At

I have a route like following where it builds the data from multiple rest calls.

App.IndexRoute = Ember.Route.extend({
  model: function() {
      var id = 1; //will get as url param later
      var modelData = {ab:{},ef:{}};
        return ajaxPromise('https://url1/'+ id +'?order=desc').then(function(data){
            modelData.ab = data.items[0];
            return ajaxPromise('https://url2/'+ id +'/?order=desc').then(function(data){
                modelData.ab.x = data.items;
                return modelData;
            })
        });
    }
});

My ajaxPromise function is as follows:

var ajaxPromise = function(url, options){
  return Ember.RSVP.Promise(function(resolve, reject) {

    var options = options || {
        dataType: 'jsonp',
        jsonp: 'jsonp'
    };

    options.success = function(data){
      resolve(data);
    };

    options.error = function(jqXHR, status, error){
      reject(arguments);
    };

    Ember.$.ajax(url, options);
  });
};

Now the issue is i know that i can use RSVP.all with promise instances but the data returned from these url has to be set to model object like above.

Also there may be few more rest calls which require data from other rest call. Is there any other way i can handle this promises.

PS: data is required right away for a single route

1

There are 1 answers

2
Kingpin2k On BEST ANSWER
App.IndexRoute = Ember.Route.extend({
  model: function() {
      var id = 1; //will get as url param later
      return Ember.RSVP.hash({
        r1: ajaxPromise('https://url1/'+ id +'?order=desc'),
        r2: ajaxPromise('https://url2/'+ id +'/?order=desc')
      });
   },
  setupController:function(controller, model){
    model.ab = model.r1.items[0];
    model.ab.x = model.r2.items;
    this._super(controller, model);
  }
);

If you have two that have to run synchronously(second depends on first), you can create your own promise, which eon't resolve until you call resolve.

   model: function() {
      var promise = new Ember.RSVP.Promise(function(resolve, reject){
        var modelData = {ab:{},ef:{}};
        ajaxPromise('https://url1/'+ id +'?order=desc').then(function(data){
          modelData.ab = data.items[0];
          ajaxPromise('https://url2/'+ id +'/?order=desc').then(function(data){
            modelData.ab.x = data.items;
            resolve(modelData);
          })
        });
      });
     return promise;
   },