在pg-promise中使用.batch参数列表

我正在运行nodejs和pg-promise,并且希望使用批处理函数来创build一个包含多个UPDATE的BEGIN和COMMIT事务。

这是我的代码:

db.tx(function (t) { return this.batch(function() { for (var i = 0; i < cars.length; i++) { return db.any('UPDATE ... ', [car_id, cars[i].votes]); } }); }) 

但是,似乎没有任何事情发生。 是不是可以像这样创build我的批处理列表?

方法批处理不作为参数的函数,它需要一个承诺数组来解决。

另外还有很多关于如何使用它的例子(在StackOverflow上),从官方文档开始: 事务 。

对于一组更新,您可以简单地创build一个更新查询数组,然后使用批处理执行它们:

 db.tx(t => { const queries = cars.map(c => { return t.none('UPDATE ... ', [c.car_id, c.votes]); }); return t.batch(queries); }) .then(data => { // success }) .catch(error => { // error }); 

额外

相同types的多个更新可以作为单个查询来执行,以获得更好的性能。 请参阅性能提升和方法helpers.update 。