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