将多个$ http返回数据分配给被调用的数组

时间:2014-06-09 04:20:47

标签: arrays json angularjs http

$scope.iter = 0;                         
$scope.myArray.forEach(function () {   
  $http.get($scope.myArray[$scope.iter].URL)
   .success(function (data) {
    $scope.myArray2.push(data);
    //$scope.myArray2[$scope.iter]=data
    });
$scope.iter++;
})           

上面的代码可以工作,但我希望myArray2中的结果与调用的顺序相同。我知道我不能指望$ scope.myArray2 [$ scope.iter] =数据工作,但这就是我需要的。

我查看了有关承诺的角度文档,但无法知道如何将其用于上述内容。

3 个答案:

答案 0 :(得分:2)

您可以将get请求中的所有promises放入数组中,并使用$q.all()创建一个在所有基础Promise解析时解析的promise。然后,您可以按照它们添加到请求数组的顺序迭代响应,并按顺序将每个响应的数据推送到数组中......

function controller ($scope, $q) {

    // ...

    var requests = [];      
    var $scope.myArray2 = [];
    angular.forEach($scope.myArray, function (value) {   
        requests.push($http.get(value.URL));
    });

    $q.all(requests).then(function(results) {
        angular.forEach(results, function(result) {
            $scope.myArray2.push(result.data);
        });
    });
}

答案 1 :(得分:0)

不要理解你想要实现的目标,但这里是控制器中简单延迟承诺的一个例子:

var firstDefer= $q.defer();

firstDefer.promise.then(function(thing){
    // here you make the first request,
    // only when the first request is completed
    //the variable that you return will be filled and
    //returned. The thing that you return in the first .then
   // is the parameter that you receive in the second .then
    return thingPlusRequestData;
}).then(function(thingPlusRequestData){
    //second request

    return thingPlusPlusRequestData;
}).then(function(thingPlusPlusRequestData){
    //and so on...
});

firstDefer.resolve(thing);
    //when you call .resolve it tries to "accomplish" the first promise
  //you can pass something if you want as a parameter and it will be
 // the first .then parameter.

希望这有助于你:D

答案 2 :(得分:0)

您通常不会按照调用$http.get(...)函数的顺序获得结果。请注意,每当http响应进入时,都会异步调用success(...)函数,并且这些响应的顺序完全不可预测。

但是,您可以通过等待所有响应完成来解决此问题,然后根据您的条件对其进行排序。

这是工作小提琴:http://fiddle.jshell.net/3C8R3/3/