Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/470.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用$q承诺在angular js中并行处理多个(循环中)异步api调用?_Javascript_Angularjs_Asynchronous - Fatal编程技术网

Javascript 如何使用$q承诺在angular js中并行处理多个(循环中)异步api调用?

Javascript 如何使用$q承诺在angular js中并行处理多个(循环中)异步api调用?,javascript,angularjs,asynchronous,Javascript,Angularjs,Asynchronous,我有一个api:{uid},我必须用不同的uid并行和异步调用多次。如何使用promise($q)在angular js中并行和异步调用?我有以下代码: 角度工厂: angular.module('witnessApp.Service') .factory('File',['$http', function ($http) { var baseUrl="http://me.apiary.com"; getFileById:function(uid){ retu

我有一个api:{uid},我必须用不同的uid并行和异步调用多次。如何使用promise($q)在angular js中并行和异步调用?我有以下代码:

角度工厂:

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调用。有可能吗?

试试这个:

$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);
}  

定义数组,将所有承诺推入其中,并调用
$q.all()

是否正在尝试等待加载所有数据?@Nico我想并行执行第一个3 api调用。在该视图之后,应渲染该视图。然后在后台进程中再次执行3 api调用。是否可能?