-1

I have two javscript async $http funtions: which I am using with angular js in a nested way to create a table dynamically.

I want some way to execute these functions to synchronously.

Right now, j loop executes only on the initial value of resultB. Once the table is compiled then the fuctB gets executed for all values of i.

$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);
  });
}
rfornal
  • 5,072
  • 5
  • 30
  • 42
rtk
  • 1
  • 3

1 Answers1

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

Please check some tutorial on Promises it will help you understand what's going on here, e.g. http://liamkaufman.com/blog/2013/09/09/using-angularjs-promises/ but there are plenty of these on internet...

csharpfolk
  • 4,124
  • 25
  • 31
  • If you *really* want to make sync call check this: http://stackoverflow.com/questions/13088153/how-to-http-synchronous-call-with-angularjs. But when working with angularjs you *want* to use promises and make async ajax calls. – csharpfolk Nov 14 '16 at 16:41