如何避免使用$ q嵌套承诺

时间:2015-01-02 00:49:53

标签: javascript q angular-promise

我试图更多地接受承诺而不是异步。我有:

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);
});

我认为通过将findRepositoryPromisethen分开,我的catch部分正确。但我仍然有getUserTeamsPromise嵌套。这似乎有些不对劲。有什么想法吗?

1 个答案:

答案 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调用中检索其结果。