Arrays 按调用顺序将多个$http返回数据分配给数组
上面的代码可以工作,但我希望myArray2中的结果与调用的顺序相同。我知道我不能期望$scope.myArray2[$scope.iter]=数据工作,但这正是我需要的Arrays 按调用顺序将多个$http返回数据分配给数组,arrays,json,angularjs,http,Arrays,Json,Angularjs,Http,上面的代码可以工作,但我希望myArray2中的结果与调用的顺序相同。我知道我不能期望$scope.myArray2[$scope.iter]=数据工作,但这正是我需要的 我查看了有关承诺的角度文档,但不知道如何将其用于上述内容。您可以将get请求中的所有承诺放入一个数组中,并使用创建一个承诺,该承诺在所有基础承诺解决时解决。然后,您可以按响应添加到请求数组的顺序迭代响应,并按顺序将每个响应的数据推送到数组中 $scope.iter = 0; $
我查看了有关承诺的角度文档,但不知道如何将其用于上述内容。您可以将get请求中的所有承诺放入一个数组中,并使用创建一个承诺,该承诺在所有基础承诺解决时解决。然后,您可以按响应添加到请求数组的顺序迭代响应,并按顺序将每个响应的数据推送到数组中
$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++;
})
我不明白你想要实现什么,但这里有一个简单的控制器延迟承诺的例子:
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);
});
});
}
希望这有助于u:D您通常不会按照调用
$http.get(…)
函数的顺序获得结果。请注意,success(…)
函数是在http响应进入时异步调用的,这些响应的顺序完全不可预测
但是,您可以通过等待所有响应完成,然后根据您的条件对它们进行排序来解决这个问题
这是一把有效的小提琴:我是否必须等待所有潜在的承诺得到解决?在myArray2中,如何在解决问题时将每个问题分配到正确的位置?您不必等待。结果数组将包含。。。好。。。按照承诺添加到
请求
数组的顺序添加“结果”(ajax响应负载)。这是工作小提琴,安东尼比我快;)。同时还要在响应中随机延迟,以证明承诺确实保持其顺序-->$q.all()在所有基础承诺都解决之前不会解决,因此,是的,使用此方法,您必须等待所有承诺都解决,然后才能迭代结果。要在他们下定决心的时候做这件事,你必须考虑其他的事情。
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.