1

I have an array of values and I want to call a promise function on every value of the array. But this has to happen sequentially. I also want to wait calling the next promise before the previous promise is resolved.

let array = [ 1, 2, 3 ];

for (var i = 0; i < array.length; i++) {
  MyPromiseFunction(array[i]).then(
     // goToNextPromise
  );
}
Jim Peeters
  • 2,573
  • 9
  • 31
  • 53

2 Answers2

2

Using the Array#reduce approach:

let array = [1, 2, 3, 4];
array.reduce((p, value) => {
    return p.then(() => MyPromiseFunction(value));
}, Promise.resolve());
Graham
  • 7,431
  • 18
  • 59
  • 84
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

You can use .reduce() for this:

let array = [ 1, 2, 3 ];

let p = array.reduce(function (p, e) {
    return p.then(function () {
        return MyPromiseFunction(e);
    });
}, Promise.resolve());
JLRishe
  • 99,490
  • 19
  • 131
  • 169