yAnTar
yAnTar

Reputation: 4610

Ember.js get 2 nested models in one route in asynchronous way

I have 2 calls to server, which proceed a long time (10-20 seconds). I need update information on page after first request (doesn't matters which) was finished. After second request finished - i need also update part of page.

How can be realised, because I've tried realise with Promises

App.IndexRoute = Ember.Route.extend({
    model: function(){
      return Ember.$.getJSON('url').then(firstMethod).then(secondMethod)
    }
})

but it doesn't work, because secondMethod will be executed after firstMethod will be finished.

Also I tried use this code:

App.IndexRoute = Ember.Route.extend({
  model: function() {
    return Ember.RSVP.hash({
      first_data: Ember.$.getJSON('url1'),
      second_data: Ember.$.getJSON('url2') 
    });
  }
});

But I have the same trouble - data will be return after 2 calls will be finished.

How run asynchronously these 2 requests and do independent update part of data on page ?

Upvotes: 1

Views: 160

Answers (1)

GJK
GJK

Reputation: 37369

I would use the PromiseProxyMixin to create object proxies that will automatically update when your promises resolve. Something like this:

model: function() {
    return Ember.Object.create({
        first_data: Ember.ObjectProxy.createWithMixins(Ember.PromiseProxyMixin, {
            promise: Ember.$.getJSON('url1')
        }),
        second_data: Ember.ObjectProxy.createWithMixins(Ember.PromiseProxyMixin, {
            promise: Ember.$.getJSON('url2')
        })
    });
}

Ember will watch your model and your two data properties for updates. Before the promises are resolved, every property asked for will return undefined. But when the promises resolve, the PromiseProxyMixin will trigger an update on the proxies, which will in turn trigger an update on all of the properties you're watching.

Upvotes: 2

Related Questions