Michael Nielsen Michael Nielsen - 2 months ago 13
Node.js Question

Using .batch with list of parameters in pg-promise

I'm running nodejs and pg-promise, and would like to use the batch function for creating a transaction with a BEGIN and COMMIT surrounding the multiple UPDATEs.

This is my code:

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

However, it seems not to be working as nothing happens. Isn't it possible to create my batch-list for input like that?


Method batch does not take a function as parameter, it takes an array of promises to resolve.

And there are plenty of examples of how to use it (on StackOverflow also), starting from the official documentation: Transactions.

For a set of updates you would simply create an array of update queries and then execute them using batch:

db.tx(function (t) {
    var queries = cars.map(function (c) {
        return t.none('UPDATE ... ', [c.car_id, c.votes]);
    return t.batch(queries);
    .then(function (data) {
        // success;
    .catch(function (error) {
        console.log("ERROR:", error.message || error);


Multiple updates of the same type can be executed as a single query, for a much better performance. See Performance Boost and method helpers.update.