angularjs – 使用Angular我们如何在完成一堆异步调用后进行调用

这是我在控制器中的代码

myFactory.getPoints().success(function (data) {
    $scope.points = data;
});

myFactory.getStates().success(function (data) {
    $scope.states = data;
});

myFactory.getLeases().success(function (data) {
    $scope.leases = data;
});

我期待$scope.leases在$scope.points和$scope.states得到它们的值之后获取值.我了解到.then的$q不是同步的.是对的吗?

答:我从答案中得出了以下内容

$q.all([
        myFactory.getPoints().success(function (data) {
            $scope.Points = data;
        }).error(function (data) {
            $scope.error = "An Error has occurred while loading Points! " + data.ExceptionMessage;
        }),   //more, more, more

    ]).then(function () {
        myFactory.getLease().success(function (data) {
            $scope.leases = data;
        }).error(function (data) {
            $scope.error = "An Error has occurred while loading Leases! " + data.ExceptionMessage;
        })
});
最佳答案
问题是success()确实返回了原始的承诺. then()调用返回一个promise(用回调返回的值解析),而.success()是更传统的注册回调方式而不返回promise.

所以适当的解决方案是

$q.all([
    myFactory.getPoints().then(function (response) {
      $scope.points = response.data;
      return response.data;
    }),

    myFactory.getStates().then(function (response) {
      $scope.states = response.data;
      return response.data;
    }),

    myFactory.getLeases().then(function (response) {
      $scope.leases = response.data;
      return response.data;
  })
]).then(function(responses) {
   // xxx
});

转载注明原文:angularjs – 使用Angular我们如何在完成一堆异步调用后进行调用 - 代码日志