在for循环中进行同步HTTP调用

making synchrnous http call in a for loop angularjs

本文关键字:同步 HTTP 调用 for 循环      更新时间:2023-09-26

我有一个url数组,要求是我必须使http。以同步方式获取请求。只有在第一个url调用成功之后,第二个url才应该被调用

for(var i in urlArray)
{
    /*do some operations and get the next url*/
    $scope.alpha(newURL);
}
$scope.alpha = function (newURL) {
    $http.get(newURL) // these calls should be synchronous
    .success(function () {
    })
    .error(function () {
    });
}

我该怎么做?

看起来您真正想要的是按顺序调用,而不一定是同步的。

在这种情况下,不要使用循环(因为它是同步的)。 只需响应上一个呼叫进行下一个呼叫。

简化的例子:

var i = 0;
makeRequest(urlArray[i], function success() {
  var nextURL = urlArray[++i];
  if (nextURL) {
    makeRequest(nextURL, success);
  }
});

其中makeRequest是发出Ajax请求并在成功时调用回调的函数:

function makeRequest(url, callback) {
    $http.get(url).success(callback);
}

我假设你想按顺序调用它们,在这种情况下,你可以使用递归,在。success回调中调用函数

var currentURL; // calculate teh currentURL
$scope.alpha(currentURL);
$scope.alpha = function (newURL) {
    $http.get(newURL) // these calls should be synchronous
    .success(function (response, status, headers, config) {
        //get the response
        //generate the new currentURL as per your need
        //keep a break condition, to exit
        $scope.alpha(currentURL);
    })
    .error(function () {
    });
}

2)或者你可以使用$q,延迟调用来实现这个

希望能有所帮助