0

I am using Angular 1.5.5 (I cannot change to another vwrsion due to project constraints) and want to chain asynchronous requests and do them one by one. I have the following:

function parseElement(element) {
  // Do things with element data
}

var myArray = [...]; // values from somewhere
var chain = $q.when();

angular.forEach(myArray, function(element) {
  var changedData = parseElement(element);

  chain = chain.then(
    MyService.myMethod(changedData, function(res) {}, function(err) {})
  );
});

My problem here is that each promise NEEDS to finish before the next loop run. This is very important since the next API call might depend on the previous calls. I don't know in advance how many elements myArray will contain, and it might be a lot of elements.

First I used $q.all because I did not know that the API call might depend on previous calls, which gave me the error. I thought that the above would change that, but id didn't, the calls are still called before the previous has finished.

Does anyone have an idea?

t.niese
  • 39,256
  • 9
  • 74
  • 101
BluePrint
  • 1,926
  • 4
  • 28
  • 49
  • In addition to the linked question's answers, the promises part of [my answer here](https://stackoverflow.com/a/43766002/157247) may be useful. – T.J. Crowder Oct 03 '18 at 09:38
  • a) You must pass a callback function to `chain.then(…)` b) Does your `MyService.myMethod(…)` call even return a promise? – Bergi Oct 03 '18 at 12:28

0 Answers0