我正在尝试更多地实现承诺,减少异步。我有:

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。这似乎是错误的。有任何想法吗?

最佳答案

警告-我对“ promise” npm模块中的Promises实现更加熟悉,但是如果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将接管其then回调的返回值状态-如果这是一个promise,则可以如上所示进行链接。这也意味着,如果return $scope.getTeamRepositories($scope.selectedTeamId);也返回了诺言,则可以在另一个链接的.then调用中检索其结果。

关于javascript - 如何避免与$ q嵌套 promise ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27736167/

10-13 05:06