nour nour nour nour - 5 months ago 9
Javascript Question

Getting my AngularJS calls in a bad order

I have a problem I am parsing some json files to an html page and the Urls are in another json file: I had a big problem because no error was detected and I was getting an empty page so while debugging using some alerts I discovered that my controller is getting an empty list:
I should have my calls in the order of my alerts:

alert(tab[i]+ " 1");
alert(list+ " 2");
alert(list+ " 3");


However I got this order:

alert(tab[i]+ " 1");
alert(list+ " 3");
alert(list+ " 2");


Here's my code


app.factory('myapp', ['$http', function($http) {
function getLists() {
$http.get('url').success(function(data) {
return data;

var tab = [];
for (i = 0; i < (data).length; i++) {
tab.push(data[i]);
}

var list = [];
for(i=0; i<tab.length; i++){
alert(tab[i]+ " 1");

$http.get(tab[i]).then(function(res) {
list.push(res.data);
alert(list+ " 2");
});

alert(list+" 3");
}

return list;
})
}

return {
getLists: getLists
};
])};




I use only AngularJS not Ajax nor jQuery.
What should I do?

Answer

I found the solution for my question well it was too simple I just had to declare list in the getLists function and add the return list outside the first http.get:

app.factory('myapp', ['$http', function($http) {        
  function getLists() {
    var list = [];
    $http.get('url').success(function(data) { 
      return data;

      var tab = [];
      for (i = 0; i < (data).length; i++) {
        tab.push(data[i]);
      }
    
      
      for(i=0; i<tab.length; i++){
        alert(tab[i]+ " 1");
        
        $http.get(tab[i]).then(function(res) {
          list.push(res.data);
          alert(list+ " 2");
        });
        
        alert(list+" 3");
      }
      
    
    })
      return list;
  }

  return {
    getLists: getLists
  };
])};