如何与正在履行依赖于其他承诺的承诺的工作? [英] How to work with promises that rely on other promises being fulfilled?
问题描述
我有一个AngularJS的承诺(用户
)依赖于另一个承诺( userTypes
)正在履行之前,我可以操纵它。从双方的承诺,结果被在控制器中使用,因此,我相信,这意味着我需要从承诺到 $范围
变量分配实际的数据:
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];
}
});
});
例如,从结果 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
}
]
这是一个人为的例子(很可能有语法错误),但我相信它可以精确地显示什么,我试图完成:我想确保我的角模型准确地重新$ P $从服务器psents对象图,所以我分配的实际 USERTYPE
对象添加到用户
,而不仅仅是重新presenting与类型ID。
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?
推荐答案
从其他承诺架构推断,你可以极有可能返回从诺言然后
,然后变成对象中的下。然后
适用于
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];
}
});;
这篇关于如何与正在履行依赖于其他承诺的承诺的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!