我试图更多地接受承诺而不是异步。我有:
var findRepositoryPromise, getUserTeamsPromise;
getUserTeamsPromise = null;
findRepositoryPromise = RepositoryService.find($stateParams.host, $stateParams.owner, $stateParams.repository);
findRepositoryPromise.then(function(response) {
$scope.selectedRepository = response.repository;
getUserTeamsPromise = TeamService.getUserTeams($rootScope.user.id);
return getUserTeamsPromise.then(function(response) {
$scope.teams = response.teams;
$scope.selectedTeam = $scope.teams[0];
$scope.selectedTeamId = $scope.selectedTeam.id;
return $scope.getTeamRepositories($scope.selectedTeamId);
});
});
findRepositoryPromise.catch(function(error) {
return toaster.pop('error', 'Error', error);
});
我认为通过将findRepositoryPromise
和then
分开,我的catch
部分正确。但我仍然有getUserTeamsPromise
嵌套。这似乎有些不对劲。有什么想法吗?
答案 0 :(得分:2)
警告 - 我更熟悉承诺中的承诺实施"承诺" npm模块,但如果q以相同的方式工作,你可以这样做:
var findRepositoryPromise;
findRepositoryPromise = RepositoryService.find($stateParams.host, $stateParams.owner, $stateParams.repository);
findRepositoryPromise.then(function(response) {
$scope.selectedRepository = response.repository;
return TeamService.getUserTeams($rootScope.user.id);
}).then(function(response) {
$scope.teams = response.teams;
$scope.selectedTeam = $scope.teams[0];
$scope.selectedTeamId = $scope.selectedTeam.id;
return $scope.getTeamRepositories($scope.selectedTeamId);
});
findRepositoryPromise.catch(function(error) {
return toaster.pop('error', 'Error', error);
});
因为promise将接管其回调的返回值的状态 - 如果这是一个promise,它可以链接,如上所示。这也意味着如果return $scope.getTeamRepositories($scope.selectedTeamId);
也返回一个promise,则可以在另一个链式.then
调用中检索其结果。