title: AngularJS : Multiple calls to a service function returning separate promises
body: <p>Ok, this is a re-posting of a previous question which I'd confused by over-simplifying the code...</p>
  
  <p>I have an angularjs factory function which queries a parse database, and returns a promise ... so far, pretty simple... however, my controller has a foreach loop which calls the function for each of a range of ids, which are meant to then resolve concurrently. The resolve doesn't work, however, and what I get back appears to be a garbled mixture of the api calls.</p>
  
  <p>Here's a simplified version of my code...</p>
  
  <pre><code>app.factory('MyFactory', function($http, $q ) {
    return {
      testFunction: function (ingredientList) {
  
        var deferred = $q.defer()
  
        ingredientIndex=-1
  
        var regulariseIngredient=function() {
  
          ingredientIndex++
  
          if (ingredientIndex&gt;ingredientList.length-1) {
            deferred.resolve(ingredientList);
            return
          }
  
          (new Parse.Query("Ingredient"))
          .equalTo("type", ingredientList[ingredientIndex].type)
          .equalTo("name", ingredientList[ingredientIndex].name)
          .include("parent")
          .find().then(function(result) {
            result=result[0]
            if(result.get("parent")) result=result.get("parent")                        
            ingredientList[ingredientIndex]=result
            regulariseIngredient();
           })                               
  
         }
         regulariseIngredient()
         return deferred.promise
      }
    }
  }
  
  app.controller('TestController', function($scope,MyFactory) {
    recipes = [ An array of objects, each with an ingredients array]
    angular.forEach(recipes, function(recipe) { 
      MyFactory.testFunction(recipe.ingredients).then(function(result) {
        console.log(result)
      })
    })
  } 
  </code></pre>
  
  <p>Bit more info on what the service actually does...</p>
  
  <p>my app has a collection of recipes, and a collection of ingredients. Each ingredient has a 'parent' which substitutes it in the 'rationalised' version. The test function loops through each ingredient, compiles the outcome and then returns a collection of substituted ingredients. The controller is looping through the recipes, so that I can check the ingredients on hand of all recipes.</p>