Reputation: 715
I have a user object that is loaded into the session at session.user
. The user can be assigned many roles. Here's what that looks like on the model:
App.User = DS.Model.extend({
roles : DS.hasMany('role'),
...
}
The roles are loaded with the user as embedded records. I can verify they are being successfully loaded into the ember-data store and the relationship between the user and the role is all good.
What I'd like to be able to do, is get one of the user's role based upon a role property. I've tried
this.get('session.user.roles').then(function (roles) {
return roles.filterBy('propertyName', 'propertyValue');
});
but I don't believe the get method returns a promise like the store.find() method does. What methods are provided to me to filter the roles?
Upvotes: 3
Views: 640
Reputation: 47367
The way you are doing it would be available as a result of a tacked on promise. Let me see if I can break it down.
Here's the long way of showing where filtered roles will be available:
var rolesPromise = this.get('session.user.roles');
var filteredRolesPromise = rolesPromise.then(function (roles) {
return roles.filterBy('propertyName', 'propertyValue');
});
filteredRolesPromise.then(function(filteredRoles){
// available here
console.log(filteredRoles.get('length'));
});
Here's the short way of showing where filtered roles will be available:
this.get('session.user.roles').then(function (roles) {
var filteredRoles = roles.filterBy('propertyName', 'propertyValue');
// available here
console.log(filteredRoles.get('length'));
});
or
var foo = this.get('session.user.roles').then(function (roles) {
return roles.filterBy('propertyName', 'propertyValue');
}).then(function(filteredRoles){
// available here
console.log(filteredRoles.get('length'));
});
returning the property to the promise just makes it available to the next tacked on promise, it doesn't assign it to the variable (foo
in the case right here).
This here helps with promises: https://www.youtube.com/watch?v=8WXgm4_V85E
Essentially I'm saying since roles is an async property you'll never be able to safely use it in a synchronous fashion.
Upvotes: 3