1

I have an array of items that I want to insert into an SQL server. I am using promises for this and in order to execute each insert sequentially I wrote the following method:

var ForeachPromise = function (array, func) {
  var promise = func(array[0]);

  for (var i=1; i < array.length; i++) {
    promise = promise.then(function() { return func(array[i]) });
  }

  return promise;
}

The idea is that when func is call it will return a promise, which will then be chained to the previous promise.

...
return ForeachPromise(type.subprocessen, function(subproces) {
    return newSubproces(subproces, typeId, dienstId, createData, s + 1);
});

I haven't actually tested it yet, but I assume that something like this will work. My question however is am I using promises correctly? Promises are great but easily misunderstood and I just want to be sure that I'm not making any fundamental mistakes.

mido
  • 24,198
  • 15
  • 92
  • 117
Jim Bauwens
  • 158
  • 1
  • 5

1 Answers1

1

Yes, that approach is fine, and works well with promises. Two minor quibbles:

  • you should take care for the case of an empty array. Start your chain with Promise.resolve() (a promise fulfilled with undefined), and begin your loop at index 0.
  • As the then callback is asynchronous, your i variable has the wrong value - the classical closure in a loop fallacy.

Using the .reduce method does help with both problems:

function foreachPromise(array, func) {
  return array.reduce(function(promise, elem, i) {
    return promise.then(function() { return func(elem) });
  }, Promise.resolve());
}
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Thanks for the great reply! I should have known about the closure in loop issue, as I have encountered it before. In any case I am glad that the approach I took was fine :) – Jim Bauwens Jul 28 '15 at 16:34