Search code examples
ember.jsember-data

Ember - findAll and promises


I have a little problem using findAll in my component. It concerns the value it returns at the end.

users: Ember.computed(function() {
return this.get('store').findAll('user');
}),

In my case, I want to get the name of the first object. So in my handlebar:

users.firstObject.name

'users' is a class in this case. But I'm trying to return directly the first object in the property, like this:

user: Ember.computed(function() {
    return this.get('store').findAll('user')
    .then(function(user){
      return user.get('firstObject');
    });
  }),

But in this case, in my handlebar, user.name is undefined and user is a promise. There is something I can't understand with promises, how they work ... Can somebody help me to get the correct user without using 'firstObject' on my users ? Thanks in advance !


Solution

  • The shortest way to solve your problem is to install an ember-promise-helpers addon and apply it in your template as follows:

    {{#if (await user)}}
      {{get (await user) 'name'}}
    {{/if}}
    

    However, AFAIK, it is not recommended to use promises as values for computed properties, although you can still do it. here I would recommend the documentation for Ember.PromiseProxyMixin as well as reading some (although older) forum threads (for instance this one).