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,003
  • 7
  • 25
  • 45

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,035
  • 17
  • 57
  • 82
T.J. Crowder
  • 959,406
  • 173
  • 1,780
  • 1,769
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
  • 95,368
  • 17
  • 122
  • 158