gpt4 book ai didi

javascript - AngularJS:forEach 和 http 获取数据 - 等待所有内容加载完毕

转载 作者:行者123 更新时间:2023-11-30 09:58:52 24 4
gpt4 key购买 nike

假设我有一篇带评论的文章。

和我的数据类似:

  {ArticleId...., someFields...., Comments: [{AuthorId:1, Text:''}, {AuthorId:2, Text:''}, {AuthorId:3, Text:''}]}

我通过获取它来获取用户数据(如头像、名称等...):/user/{id}

(但我只在用户点击评论后加载它...)

$scope.getUserData = function(el) {
$http.get(settings.apiBaseUri + '/app/users/' + el.AuthorId, {
headers: {
'Content-Type': 'application/json',
'Pragma': 'no-cache',
'Cache-Control': 'no-cache',
'If-Modified-Since': ''
}
})
.success(function(response) {
/*store some data*/
});
});

$scope.getArticleData = function(){
angular.forEach($scope.article.Comments, function(el) {
$scope.getUserData(el.AuthorId);
});
/*How here i could wait untill my forEach done all work (also all http data was loaded) and only then run my new method?*/
};

我怎么能等到我的 forEach 完成所有工作(也加载了所有 http 数据)然后才运行我的新方法?

最佳答案

我想你可以为此使用一个 promise 数组,其中包含由 $http 创建的 promise。像这样的东西:

$scope.getUserData = function(el) {
var promise = $http.get(settings.apiBaseUri + '/app/users/' + el.AuthorId, {
headers: {
'Content-Type': 'application/json',
'Pragma': 'no-cache',
'Cache-Control': 'no-cache',
'If-Modified-Since': ''
}
})
.success(function(response) {
/*store some data*/
});
return promise;
});

$scope.getArticleData = function(){
var promises = [];
angular.forEach($scope.article.Comments, function(el, promises) {
promises.push($scope.getUserData(el.AuthorId));
});
$q.all(promises).then(/*Whatever you want to do*/);
};

或者像@sdgluck 建议的那样更漂亮:

$scope.getArticleData = function(){
var promises = $scope.article.Comments.map(function() {
return $scope.getUserData(el.AuthorId);
});
$q.all(promises).then(/*Whatever you want to do*/);
};

关于javascript - AngularJS:forEach 和 http 获取数据 - 等待所有内容加载完毕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32652459/

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