I was trying to chain a bunch of API calls based on a specific max count, until the offset specified for the API call does not exceed the max count. The offset is intended to increase by a constant for every API call.
First attempt was trying to use a while loop to get offset for before adding every call:
var processAll = function() { //initial offset value zero
      var offset = 0;
      var promiseChain = $q.when();
      while(offset < maxCount) {
        promiseChain = promiseChain.then(function () {
          return getData(offset).then(function (result) {
            // processing result data
          });
        });
        offset += 200;
      }
      return promiseChain;
    };
However, the above code resulted in getData being called with the wrong value for offset.
Attempted the same with a forEach loop, on a list of offsets.
    var processAll = function() {
      var promiseChain = $q.when();
      var offsetList = divideIntoList(); // gets a list like [0, 200, 400] etc based on maxCount
      offsetList.forEach(function (offset) {
        promiseChain = promiseChain.then(function () {
          return getData(offset).then(function (result) {
            // processing result data
          });
        });
      });
      return promiseChain;
    };
This approach worked successfully.
Is the while loop approach not compatible with how AngularJS handles promises? Found a question that solves a similar problem here. Is this just related to while loop behaviour or does $q.when() have something to do with it as well?
