Reputation: 8344
I have an AngularJS promise (users
) that relies on another promise (userTypes
) being fulfilled before I can manipulate it. The results from both promises are being used in the controller and as such, I believe that means I need to assign the actual data from the promise to a $scope
variable:
// this is all in my controller somewhere
userService.getUserTypes().then(function( data ) {
$scope.userTypes = data;
}).then(function( data ) {
userService.getUsers().then(function( data ) {
$scope.users = data;
for( var user in $scope.users ) {
$scope.users[ user ].userType = $filter("filter")( $scope.userTypes, { id: $scope.users[ user ].userTypeID })[0];
}
});
});
Example results from userService
:
// userService.getUserTypes()
[
{
"id": 1,
"type": "Administrator"
},
{
"id": 2,
"type": "User"
}
]
// userService.getUsers()
[
{
"id": 1,
"name": "Sean Walsh",
"userTypeID": 2
},
{
"id": 2,
"name": "Joe Blow",
"userTypeID": 2
},
{
"id": 3,
"name": "Joe Administrator",
"userTypeID": 1
}
]
That's a contrived example (quite possibly with syntax errors), but I believe it accurately displays what I'm trying to accomplish: I want to make sure that my Angular model accurately represents the object graph from the server, so I am assigning the actual userType
objects to the user
rather than just representing the type with an ID.
My concern with this approach is that I can already see a little bit of "callback hell" starting with the nested then()
calls. Is there a better way to tackle this problem?
Upvotes: 0
Views: 188
Reputation: 97631
Extrapolating from other promise architectures, you can most likely return a promise from then
, which then becomes the object the next .then
is applied to.
// this is all in my controller somewhere
userService.getUserTypes().then(function( data ) {
$scope.userTypes = data;
}).then(function(data) {
return userService.getUsers();
}).then(function( data ) {
$scope.users = data;
for( var user in $scope.users ) {
$scope.users[ user ].userType = $filter("filter")( $scope.userTypes, { id: $scope.users[ user ].userTypeID })[0];
}
});;
Upvotes: 1