我有两个javscript async $ http功能:我以嵌套方式使用角度j来动态创建表。
我想要一些方法来同步执行这些功能。
现在,j循环仅对resultB的初始值执行。编译完表后,将为i的所有值执行fuctB。
$scope.funcA = function() {
$http({
method : 'GET',
url : url,
}).then(function successCallback(response) {
$scope.resultA = response.data;
//process based on $scope.resultA
for (var i = 0; i < $scope.resultA .length; i++){
$scope.funcB($scope.resultA[i][0]);
for(j=0; j<$scope.resultB .length; j++){
//process based on $scope.resultB
}
}
$compile(/* document element*/);
}, function errorCallback(response) {
console.log(response.statusText);
});
}
$scope.funcB = function(k){
$http({
method : 'GET',
url : url+k
data: k ,
}).then(function successCallback(response) {
return $scope.resultB = response.data;
}, function errorCallback(response) {
console.log(response.statusText);
});
}
答案 0 :(得分:0)
$scope.funcB = function(i) {
// return promise
return $http({....
data: i ;
$scope.resultB = response.data;
};
}
$http{.....
$scope.resultA =response.data;
for(var i =0; i< $scope.resultA.length; i++{
process based on i value
$scope.funcB(i).then(function() {
// execute this part after promise completed (request B has ended and returned result)
for(var j =0; j<$scope.resultB.length;j++{
process based on i and j;
}
}
compile(the document element);
});
}
请查看一些有关Promises的教程,它可以帮助您了解这里发生了什么,例如: http://liamkaufman.com/blog/2013/09/09/using-angularjs-promises/但互联网上有很多这些......