多个Js请求的同步

时间:2015-02-17 04:09:34

标签: javascript angularjs asynchronous promise ngresource

我在尝试在AngularJS中同步多个异步请求时遇到了一些问题。 我将解释我拥有的和我需要的东西。

  • 用户有很多网站
  • 每个网站都有许多订阅
  • 每个网站都有很多交易
  • 每笔交易都与订阅相关联

我通过第三方API获取订阅和交易。它们中的每一个都返回具有关联Id的元素阵列。 所以我需要为每个数组的每个元素发出请求并关联两个结果。

我不知道该怎么做,或者我怎么处理这件事。 任何帮助都是值得欣赏的。

$q.all([
    PaymentService.getTransactions(profile.payment.account_code),
    SiteService.getAll(),
    PaymentService.getUserSubscriptions(profile.payment.account_code)
  ]).then(function (data) {
    var transactions = data[0];
    var user_sites = data[1];
    var user_subscriptions = data[2];
    // returns site-by-site
    angular.forEach(user_sites, function (site) {
      SiteService.loadSite(site.$value).then(function (loaded_site) {
        loaded_site.transactions = [];
        loaded_site.subscriptions = [];
        angular.forEach(user_subscriptions, function (subscription) {
          console.log('SUBSCRIPTION: ', subscription);
          if ( subscription.uuid === loaded_site.recurly_subscription_uuid ) {
            loaded_site.subscriptions.push(subscription);
          }
        });
        angular.forEach(transactions, function (transaction) {
          if ( transaction.subscription ) {
            if ( getSubscriptionId(transaction.subscription.$.href) === loaded_site.recurly_subscription_uuid ) {
              loaded_site.transactions.push(transaction);
            }
          }
        });
        $scope.sites.push(loaded_site);
      });
    });
  })

1 个答案:

答案 0 :(得分:0)

您可以重新应用$q.all技术:

$q.all([
    PaymentService.getTransactions(profile.payment.account_code),
    SiteService.getAll(),
    PaymentService.getUserSubscriptions(profile.payment.account_code)
  ]).then(function (data) {
    var transactions = data[0];
    var user_sites = data[1];
    var user_subscriptions = data[2];

    var promises = [];

    angular.forEach(user_sites, function (site) {
      promises.push(SiteService.loadSite(site.$value));
    });


    $q.all(promises).then(function(loaded_sites) {
      angular.forEach(loaded_sites, funciton(loaded_site) {

        loaded_site.transactions = [];
        loaded_site.subscriptions = [];


        angular.forEach(user_subscriptions, function (subscription) {
          console.log('SUBSCRIPTION: ', subscription);
          if ( subscription.uuid === loaded_site.recurly_subscription_uuid ) {
            loaded_site.subscriptions.push(subscription);
          }
        });

        angular.forEach(transactions, function (transaction) {
          if ( transaction.subscription ) {
            if ( getSubscriptionId(transaction.subscription.$.href) === loaded_site.recurly_subscription_uuid ) {
              loaded_site.transactions.push(transaction);
            }
          }
        });

        $scope.sites.push(loaded_site);

      });

     });

  });