javascript - 如何使用 $q promise 在 angular js 中并行处理多个(循环内)异步 api 调用?

标签 javascript angularjs asynchronous

我有一个 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,
    }

  }]);

Angular Controller :

'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。之后应该渲染 View 。然后在后台进程中再次调用 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);
}  

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

关于javascript - 如何使用 $q promise 在 angular js 中并行处理多个(循环内)异步 api 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25126810/

相关文章:

javascript - 如何从jquery下拉按钮控制检查元素

javascript - AngularJs 表单发布数据在我的 spring Controller 中给出空值

javascript - 当我动态更改 html 时,ng-bind-html 中的 ng-click 不触发

javascript - 如何在 Angular 中移动图像( Blob )数组?

javascript - 基准异步代码 (Benchmark.js, Node.js)

java - GWT : Replacing blocking calls with async RPCs

javascript - 开 Jest 测试: Awating multiple promises in connected component

javascript - 如何保护 Socket.IO?

javascript - Gulp 正在创建一个目录而不是文件

javascript - 表格单元格元素中的 Angular 嵌入