【问题标题】:how to use $q promises to work with multiple(in loop) asynchronous api call parallely in angular js?如何使用 $q 承诺在角度 js 中并行处理多个(循环中)异步 api 调用?
【发布时间】:2014-08-04 20:15:01
【问题描述】:

我有一个 api:“http://me.apiary.com/1/user/{uid}”,我必须使用各种 uid 多次并行和异步调用它。如何使用 promise($q) 在 angular js 中并行和异步调用?我有以下代码:

Angular 工厂:

angular.module('witnessApp.Service')
  .factory('File',['$http', function ($http) {
    var baseUrl="http://me.apiary.com";
      getFileById:function(uid){
      return  $http({
          method: 'GET',
          url: baseUrl+'/1/user/'+uid
        });
      }
    }


    return {
      getFileById:fileTools.getFileById,
    }

  }]);

角度控制器:

'use strict';
angular.module('witnessApp.Controller')
  .controller('shareCtrl',['$scope','FileShare','$window','$routeParams','shareImgId','File', function ($scope,FileShare,$window,$routeParams,shareImgId,File) {
    var id=$window.localStorage.id;
    $scope.sharedImagesByID=[];
    var uids=[1,2,3,4,5,6,7,8,9,0,11,10,12,13,14];

    $scope.getFileById=function(){
      for(var key in uids){
        File.getFileById(uids[key])
        .success(function(data, status, headers) {
        $scope.sharedImagesByID.push(data.data)
      })
      .error(function(data, status, headers, config) {
        console.error('error in loading File');
      });


  }

}

我尝试使用 $q.all([])。但是我如何使用 $q.all() 处理循环。我不知道。请建议我怎么做? 是否可以先并行调用 3 个 api。之后应该渲染视图。然后在后台进程中再次调用 3 个 api。依此类推,直到最后一次 api 调用。有可能吗?

【问题讨论】:

  • 您是否要等待所有数据加载完毕?
  • @ Nico 我想先并行调用 3 个 api。之后应该渲染视图。然后在后台进程中再次调用 3 个 api。这可能吗?

标签: javascript angularjs asynchronous


【解决方案1】:

试试这个:

$scope.getFileById = function() {

    var promises = [];
    for(var key in uids) {
       var promise = File.getFileById(uids[key]);

       promise.success(function(data, status, headers) {
            $scope.sharedImagesByID.push(data.data);
       });

       promise.error(function(data, status, headers, config) {
            console.error('error in loading File');
       });

       promises.push(promise);
     }

     $q.all(promises);
}  

定义数组,将所有 promise 放入其中,然后调用 $q.all();

【讨论】:

    猜你喜欢
    • 2019-10-17
    • 2014-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    • 2016-03-15
    相关资源
    最近更新 更多