这是为数组生成一连串承诺的好方法吗?

时间:2015-07-28 15:07:26

标签: javascript promise

我有一系列要插入SQL服务器的项目。我正在使用promises,为了顺序执行每个插入,我编写了以下方法:

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;
}

这个想法是,当func被调用时,它将返回一个promise,然后将其链接到前一个promise。

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

我还没有真正测试过它,但我认为这样的事情会起作用。然而,我的问题是我是否正确使用了承诺?承诺是伟大的,但很容易被误解,我只是想确保我没有犯任何根本性的错误。

1 个答案:

答案 0 :(得分: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());
}