0

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?

Aastha Bist
  • 324
  • 2
  • 11
  • 1
    "*the above code did not result in getData being called.*" - are you sure there? It should get called just fine, for the correct number of times - but [with the wrong value for `offset`](https://stackoverflow.com/q/750486/1048572) – Bergi Aug 05 '22 at 02:14
  • 1
    You are right. I was checking inside then. It is called with the wrong value. This explains what is happening. Thanks. – Aastha Bist Aug 05 '22 at 02:30

0 Answers0