这是为数组生成承诺链的好方法吗? [英] Is this a good way to generate a chain of promises for an array?

查看:31
本文介绍了这是为数组生成承诺链的好方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组要插入 SQL 服务器的项目.我为此使用了 Promise,为了按顺序执行每个插入,我编写了以下方法:

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

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

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

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

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.

推荐答案

是的,这种方法很好,并且适用于 promise.两个小问题:

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

  • 你应该注意空数组的情况.用 Promise.resolve()(一个用 undefined 实现的承诺)开始你的链,并从索引 0 开始你的循环.
  • 由于 then 回调是异步的,您的 i 变量具有错误的值 - 经典的 循环闭包谬误.
  • 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.

使用 .reduce 方法 确实有助于解决这两个问题:

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

这篇关于这是为数组生成承诺链的好方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆