There is such a code

$http.get('articles/articles.json').success(function(data){ $scope.articles = data; angular.forEach(data, function(article) { $scope.article = []; var url = 'articles/'+ article.year +'/' + article.mounth + '/articles' + article.titlemounth + '.json'; console.log(url); $http.get(url).success(function(data){ console.log(url); $scope.article.push(data); data = ''; }); }); }); 

Here is the output of the first log

 articles/2016/april/articlesApril.json articles/2016/may/articlesMay.json articles/2016/jun/articlesJune.json 

But the second

 articles/2016/april/articlesApril.json articles/2016/jun/articlesJune.json articles/2016/may/articlesMay.json 

Ie http does not work in the order in which it was intended. Please tell me what you can do about it.

  • since $http sends asynchronous requests, and the logs are displayed in the answers, it is impossible to guarantee in this case that the answers will come in the same order as there were requests - Grundy
  • But do not tell me how the cycle should look so that the sending of requests was in a certain sequence and the output was also in the same order? - Evgeny Nadolinsky 5:43 pm
  • besides, at each iteration of the loop, the value of $ scope.article is overwritten , that is, in any case there will be only one answer - Grundy
  • here the question is. what is really needed: if the requests should be executed in turn. that is, do not send the next question before the answer comes from the current one, or the answers must be saved into the array in the order in which they were sent. - Grundy
  • Answers should be saved to the array in the order in which they were sent, now once out of ~ 8 requests, the answers to the array are written in random order. - Evgeny Nadolinsky pm

1 answer 1

When using forEach, there is access to the number of the current request, so the answer must simply be put on the desired index:

 $scope.articles = []; angular.forEach(data, function(article, index) { $scope.article = []; var url = 'articles/'+ article.year +'/' + article.mounth + '/articles' + article.titlemounth + '.json'; console.log(url); $http.get(url).success(function(data){ console.log(url); $scope.article[index] = data; }); }); 

The order of the logs is also arbitrary, but the output will be in the order in which they were sent.