使用$ q.所有这些都是为了让同步HTTP调用无法正常工作

using $q.all for making synchronous http calls not working angularjs

本文关键字:调用 常工作 工作 HTTP 同步 所有这些 使用      更新时间:2023-09-26

我遇到了以下问题,无法继续。我尝试了一些解决方案,张贴在不同的问题,但无法得到它的工作

在我的控制器,我有一个$scope.init()函数。我有一个for循环在它调用一个函数来制作http。获取对不同url的调用,每个url依赖于前一个调用的数据,所以我需要它是同步的

$scope.init = function() {
    decodedURL = $routeParams.url;
    //evaluate some variables, ampIndex is > -1 here
    for( var i=0; ampIndex > -1; ++i)
    {
        decodedURL = decodedURL.substring(ampIndex+1, decodedURL.length);
        ampIndex = decodedURL.indexOf("&");
        $scope.getNextList(i);
        /* above function call makes the http.get call to the currentURL based on
           decodedURL, and the data is stored in variable[i+1], so for the next
           iteration, the calls should be synchronous
        */
        $q.all(asyncCall).then(function (data) {var j;} );
        /* I wrote the above dummy statement so that it is executed only after
           http.get in $scope.getNextList() function is successful, but it is
           not working 
        */
    }
};

$scope.getNextList = function(index) {
    // $currentURL is calculated
    var hello = _helpers.server.http($http, $scope.currentURL) {
        .success( function(response) {
        })
        .error( fucntion(errResponse) {
        });
    asyncCall.push(hello);
};

如何解决这个问题?

这样写怎么样?

http://plnkr.co/edit/pjWbNX1lnE2HtaNs1nEX?p =

预览
$scope.init = function ( ){
  for (var i=0; i < 10; i++) {
    $scope.getNextList(i) // push calls into array
  };
  var index = 0;
  function makeCall() {
    $scope.asyncCall[index]
    .success(function(data) {
      if (index < $scope.asyncCall.length - 1) {
        console.log(index);
        index += 1;
        makeCall();
      }
      else {
        console.log(index); // last call
      }
    })      
  }
  makeCall();
};