如何在服务和控制器中使用 angularjs 承诺链?

How can I use angularjs promise chain in a service and controller?

我在网上找到了这个 plnkr link,但我需要将它与 2 或 3 个以上的 ajax 调用一起使用,这些调用不需要来自第一个 ajax 调用的参数。我该如何处理错误?

var app = angular.module("app", []);

app.service("githubService", function($http, $q) {

  var deferred = $q.defer();

  this.getAccount = function() {
    return $http.get('https://api.github.com/users/haroldrv')
      .then(function(response) {
        // promise is fulfilled
        deferred.resolve(response.data);
        return deferred.promise;
      }, function(response) {
        // the following line rejects the promise 
        deferred.reject(response);
        return deferred.promise;
      });
  };
});

app.controller("promiseController", function($scope, $q, githubService) {

  githubService.getAccount()
    .then(
      function(result) {
        // promise was fullfilled (regardless of outcome)
        // checks for information will be peformed here
        $scope.account = result;
      },
      function(error) {
        // handle errors here
        console.log(error.statusText);
      }
    );
});

http://plnkr.co/edit/kACAcbCUIGSLRHV0qojK?p=preview

您可以使用 $q.all

var promises=[
$http.get(URL1),
$http.get(URL2),
$http.get(URL3),
$http.get(URL4)
];

$q.all(promises).then(function(response){
console.log('Response of Url1', response[0]);
console.log('Response of Url2', response[1]);
console.log('Response of Url3', response[2]);
console.log('Response of Url4', response[3]);
}, function(error){

});

我已经用 $q

分叉了你的 plunkr

在这种情况下使用 $q.all。它会同时调用 getAccountgetSomeThing api。

var app = angular.module("app", []);

app.service("githubService", function($http, $q) {

  return {

    getAccount: function () {
      return $http.get('https://api.github.com/users/haroldrv');
    },

    getSomeThing: function () {
      return $http.get('some thing url');
    }
  };

});

app.controller("promiseController", function($scope, $q, githubService) {

  function initData () {
    $q.all([githubService.getAccount(), githubService.getSomeThing()])
      .then(
        function (data) {
          $scope.account = data[0];
          $scope.someThing = data[1];
        },
        function (error) {

        }
      );
  }
});

首先,你应该为每个你想要 return 承诺的 ajax 调用创建 deferred 局部变量。因此,您必须创建 2-3 个函数(与您的 ajax 调用一样多)并将它们保存在一个数组中。那么你应该使用:

$q.all([ajax1,ajax2,ajax3]).then(function(values){
    console.log(values[0]); // value ajax1
    console.log(values[1]); // value ajax2
    console.log(values[2]);}); //value ajax3

示例:

function ajax_N() {
   var deferred = $q.defer();

    http(...).then((response) => {
      deferred.resolve(response);
   }, (error) => {
      deferred.reject(error);
   });

   return deferred.promise;
}

$q.all([
        ajax_1,ajax_2,ajax_3
     ]).then(function(values) {        
          console.log(values); 
          return values;
        });