Reputation: 3781
I'm trying to get two get 2 lists of blog posts from 2 categories (news and events), then display them in 2 different columns of my home page. It is required for me to perform 2 separate Ajax calls to get those blog posts. I do not use ember-data for this operation, as I don't see the advantage of using it in this scenario (but I may be wrong).
export default Ember.Route.extend({
setupController(controller, model) {
var wpUrl = 'http://public-api.wordpress.com/rest/v1/sites/company.wordpress.com/posts/?number=2&category=';
Ember.$.ajax({ url: wpUrl + 'news', dataType: "jsonp", type: 'GET' }).then(function (data) {
controller.set('news', data.posts);
});
Ember.$.ajax({ url: wpUrl + 'events', dataType: "jsonp", type: 'GET' }).then(function (data) {
controller.set('events', data.posts);
});
}
});
The above code works. But from what I read in the Ember documetation, I should be getting those data in the model
hook (instead of setupController
) to take advantage of promises. So I tried to re-write my code this way:
export default Ember.Route.extend({
model() {
var wpUrl = 'http://public-api.wordpress.com/rest/v1/sites/company.wordpress.com/posts/?number=2&category=';
return {
news: function () {
return Ember.$.ajax({ url: wpUrl + 'news', dataType: "jsonp", type: 'GET' }).then(function (data) {
return data.posts;
})
},
events: function () {
return Ember.$.ajax({ url: wpUrl + 'events', dataType: "jsonp", type: 'GET' }).then(function (data) {
return data.posts;
})
}
};
}
});
But this does not work. The Ajax calls are done but too late, after the page has rendered. I'm not sure here what I'm doing wrong. Would there be any advantage of using ember-data for that scenario?
Upvotes: 10
Views: 3888
Reputation: 8732
You can return an hash of Promises with RSVP.hash()
You could do this:
export default Ember.Route.extend({
model() {
var wpUrl = 'http://public-api.wordpress.com/rest/v1/sites/company.wordpress.com/posts/?number=2&category=';
return new Ember.RSVP.hash({
news: Ember.$.ajax({ url: wpUrl + 'news', dataType: "jsonp", type: 'GET' }),
events: Ember.$.ajax({ url: wpUrl + 'events', dataType: "jsonp", type: 'GET' })
});
}
});
Read more about promises in Ember here
Upvotes: 13
Reputation: 688
You return an object containing two promises, rather than an actual promise. What you need is to build your own promise (Ember.RSVP.Promise) that will be resolved once both of the inner promises resolves.
Upvotes: 2