gpt4 book ai didi

javascript - 在另一个 Ajax 请求中处理多个 Ajax 请求

转载 作者:行者123 更新时间:2023-11-30 16:32:17 25 4
gpt4 key购买 nike

我正在使用 angularjs 的 $http 方法来获取多个“父”元素。在此 Ajax Calls .success 方法中,我必须遍历父元素,并对每个父元素使用另一个 Ajax 调用,以获取其各自的子元素。最后我想要的是一个包含所有子元素对象的数组,因此我可以使用 ng-repeat 显示它们。这就是为什么我想首先收集数组中的所有子元素,然后将该数组写入我用来显示的范围数组,因此只有在收集所有子元素时,angular 才会更新。我不是那么精通使用 promise ,但我认为这应该可以通过使用它们来实现。结构基本上是:

.success(function(parentElements){
var tempChildElements = [];
$.each(parentElements, function(i, parentElement){
getChildElements(parentElement)
.success(function(childElements){
tempChildElements.concat(childElements);
})
})
});
$scope.childElements = tempChildElements;
});

基本上,我需要知道 jQuery.each 中的所有请求何时完成。

编辑:

因此,我更改了我的代码以合并您的答案,我想我已经接近了,但它仍然无法正常工作。我得到的是:

$scope.loadChildren = function(){
var tempchildren = [];
var promises = [];
restApi.getOwnparents() //Returns $http.get promise
.then(function(parents){

parents.data.forEach(function(parent, i, parents){
promises.push(restApi.getOwnchildren(parent) //Returns $http.get promise
.then(function(children){

tempchildren = tempchildren.concat(children.data);
},function(msg){
console.log(msg);
}));

});
}, function(msg){
console.log(msg);
});
$q.all(promises).then(function(data){
//Never gets called
$scope.currentElements = tempchildren;
console.log(tempchildren);
});
};

编辑 2:我使用你们的建议让它工作,下面是我的代码。欢迎分享改进。

$scope.loadparents = function(){
var tempchildren = [];
var promises = [];
restApi.getOwnparents()
.then(function(parents){
parent.data.forEach(function(parent, i, parents){
promises.push(restApi.getOwnchildren(parent));
});
$q.all(promises).then(function(data){
console.log(data);
data.forEach(function(children){
tempchildren = tempchildren.concat(children.data);
});
$scope.currentElements = tempchildren;
});
});

};

最佳答案

这样的事情是有可能的。使用该元素循环调用 parentElements 调用 getChildElements。但是,如果您返回 $http 调用,则 getChildElements 的响应将是一个 promise ,因此将其插入一个数组并将该数组传递给 $q.all。当您所有的 ajax 调用都解决时,$q.all 也会解决。

 var parentElements = [10, 20, 30, 40],
promises = [];

parentElements.forEach(function(i){
//Each method is actually called here
promises.push(getChildElements(i));
});

//$q.all will resolve once all of your promises have been resolved.
$q.all(promises)
.then(function (data){
//handle success
console.log('All Good', data);
//Modify your response into what ever structure you need, map may be helpfull
$scope.childElements = data.map();
});

当数组传递给 $q.all 时,很可能你的 ajax 调用不会被解析,但是 promises 的另一个好处是即使它们都被解析了 $q .all 将立即解析。

查看实际效果。 http://jsfiddle.net/ht9wphg8/

关于javascript - 在另一个 Ajax 请求中处理多个 Ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33155025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com