0

I need two independend arrays to work with them inside function. So I returning promises. But when it's getting to arrayOne.length it's not waiting untill promises resolve. How to make it work then?

this.workWithArrays = function () {
   var arrayOne = this.getArrayOne();
   var arrayTwo = this.getArrayTwo();

   for (var i = 0; i < arrayOne.length; i++) {
       .....
   }

getArrayOne and getArrayTwo are mostly identical:

this.getArrayOne = function() {
   return $http.get('/1').then(
      function success(response) {
         return response.data;
      },
      function error(data) {
         console.log(data);
      }
   );
}
ottercoder
  • 852
  • 1
  • 12
  • 31

1 Answers1

1

Inject $q service and use it's all method:

this.workWithArrays = function () {
 var arrayOne = this.getArrayOne();
 var arrayTwo = this.getArrayTwo();
 $q.all([arrayOne,arrayTwo]).then(function(responses){
   // your logic that needs to run after both  promises resolve
 });
T J
  • 42,762
  • 13
  • 83
  • 138