Promises in a loop


#1

hi,

my problem is a more generell problem. i am asking here to find out, if there is a special angularjs feature, which reduces the complexity of a for loop with promises.

a short example:
i got a function surrounded by a $q. in this function, a code is iterated through a for-loop. if the value of the code is “0”, continue with the next step in the for-loop. otherwise, go through some other asynchronous service functions to set the variable myData right.

return $q(function (resolve, reject) {
  var pCode = "1050";
  var myData = {};
    for (var i = 0; i <= pCode.length; i++) {
      var lcHumanIdx = i + 1;
      if (pCode[i] === "0") {
          continue;
          i = i + 1;
      } else {
          if (lcHumanIdx === 1) {
              SomeService.getTranslationByID(pCode[i])
                  .then(function (pElement) {
                      if (pCode[i + 1] !== "-") {
                          myData.translation = pElement;
                      } else {
                          OtherService.getSomethingElse()
                              .then(function (pOtherElement) {
                                  myData.otherTranslation = pOtherElement;
                          })
                      }             
             ...
             resolve(myData);
        });

before i go and code, i just wanted to ask, whats the best practise to realize such a problem. are there any specific angularjs solutions (like bluebirds promiseWhile)? the problem in this example is, that the variable myData is {} every time!


#2

You want $q.all: https://docs.angularjs.org/api/ng/service/$q#all