Angular promise 应该调用其他 promise

Angular promise should call other promises

我的状态解析为:

resolve: {
              accounts: function(utils) {
                return utils.getAccounts();
              },
              data: function(utils) {
                return utils.getData();
              },
              termsData: function(utils) {
                return utils.getTerms();
              }
            }

我需要确保仅在 angular resolve.

中返回 accounts 后才调用 datatermsData

getAccounts 函数类似于:

 function getAccounts() {
            var deferred = $q.defer();
            Restangular.setBaseUrl(baseUrl());
            var accountsService = Restangular.all(accountsUrl);
            accountsService.post({headers}).then(function(data) {
              deferred.resolve(data);
            }, function(ex) {
              deferred.reject(ex);
            });
            return deferred.promise;
          }

您可以在 getAccounts 函数承诺得到解决后调用其他两个,然后使用 getDatagetTerms 承诺执行 return 数据 $q.all

resolve: {
    accounts: function(utils, $q) {
        return utils.getAccounts().then(function(accounts){
            return $q.all([accounts, utils.getData(), utils.getTerms()])
        });
    }
}

控制器

app.controller('mainCtrl', function($q, $scope, accounts){
    console.log("accounts", accounts[0])
    console.log("getData Response", accounts[1])
    console.log("getTerms Response", accounts[2])
})

假设您需要异步获取所有数据,您可以简单地重构代码以利用承诺模式。

var getAccounts = function(...) {
  return new Promise(resolve, reject) {
    ... do something and resolve or reject
  };
};

var getTermsData = funciton= function(...) {
  return new Promise(resolve, reject) {
    ... do something and resolve or reject
  };
};

var getData = = function(...) {
  return new Promise(resolve, reject) {
    ... do something and resolve or reject
  };
};

getAccounts.then(function(accounts) {
  return getTermData();
}.then(function(termData) {
  return getData(data);
}.catch(function() {
  // something went wrong!
}

您可以像我想您在控制器中那样将帐户添加为依赖项:

resolve: {
          accounts: function(utils) {
            return utils.getAccounts();
          },
          data: ['accounts', 'utils', function(accounts, utils) {
              accounts.then(function(data){
                 return utils.getData();
              }, function(data){
                 return $q.reject();
              });
          }]
        }
}