Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronous data calls in Ember.js

I am trying to do the following when visiting reviews/show (/reviews/:id):

  • Load two models from the server: One review and one user.
  • I only have access to the review's id, so I need to load it first, to get the userId
  • And then, when that has finished loading and I now have the userId, query the user using the userId attribute from the review
  • Finally, return both of these in a hash so I can use them both in the template

So two synchronous database queries, and then return them both at once in the model hook of the route.

I don't mind if it's slow, it's fast enough for now and I need it to work now.

This is what I've tried and it doesn't work:

reviews/show.js

export default Ember.Route.extend({
  model: function(params) {
    var user;
    var review = this.store.findRecord('review', params.id).then(
      function(result) {
        user = this.store.findRecord('user', result.get('userId'));
      }
    );

    return Ember.RSVP.hash({
      review: review,
      user: user
    });
  }
});
like image 779
Marco Prins Avatar asked Oct 12 '25 08:10

Marco Prins


1 Answers

You can do this:

export default Ember.Route.extend({
  model: function(params) {
    var reviewPromise = this.store.findRecord('review', params.id);
    return Ember.RSVP.hash({
      review: reviewPromise,
      user: reviewPromise.then(review => {
        return this.store.findRecord('user', review.get('userId'));
      })
    });
  }
});

The reason why user is undefined is because it hasn't been assigned in your first promise until the review is resolved, but Ember.RSVP.hash has received user as undefined.

like image 161
Kit Sunde Avatar answered Oct 15 '25 00:10

Kit Sunde