【问题标题】:making synchrnous http call in a for loop angularjs在for循环angularjs中进行同步http调用
【发布时间】:2015-07-08 12:27:05
【问题描述】:

我有一个 url 数组,要求我必须以同步方式发出 http.get 请求。只有第一个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 () {
    });
}

我该怎么做?

【问题讨论】:

  • 你尝试过使用 $q 吗?

标签: javascript angularjs http get


【解决方案1】:

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

在这种情况下,不要使用循环(因为它是同步的)。只需拨打下一个电话以响应上一个电话。

简化示例:

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

【讨论】:

  • 如何定义 makeRequest?语法,我的意思是....使用上面的代码,我得到“ReferenceError: makeRequest is not defined”
  • 就像您定义任何其他函数一样,例如function makeRequest(url, callback) { ... }。你可以随意命名,这只是一个例子。
  • 好吧,你得把...换成函数的代码。
  • 在那里,我更新了我的答案。没想到定义函数是个大问题。
【解决方案2】:

我假设你想按顺序调用它们,在这种情况下,你可以使用递归之类的东西,在 .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, deferred calls 来实现这个

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    • 2021-06-15
    • 2019-01-29
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多