[英]How to work with promises that rely on other promises being fulfilled?
我有一個AngularJS承諾( users
),它依賴於我可以操縱它之前實現的另一個承諾( userTypes
)。 來自兩個promise的結果都在控制器中使用,因此,我認為這意味着我需要將promise中的實際數據分配給$scope
變量:
// 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
}
]
這是一個人為的示例(可能有語法錯誤),但是我相信它可以准確顯示我要完成的工作:我想確保我的Angular模型能夠准確地表示服務器上的對象圖,因此我要分配實際的user
userType
對象,而不僅僅是用ID表示類型。
我對這種方法的擔心是,從嵌套的then()
調用開始,我已經看到了一些“回調地獄”。 有沒有更好的方法來解決這個問題?
從其他promise體系結構推斷,您很可能會then
返回promise, then
promise將成為下一個.then
應用於的對象。
// 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];
}
});;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.