Sails.js best practice in using transactions with promises (Postgres)

后端 未结 2 1245
囚心锁ツ
囚心锁ツ 2021-02-01 06:51

I\'m using sails 0.9.16 with Postgres and my question is: what is the best way to execute transaction using current API with promises? May be there is something better than:

2条回答
  •  旧巷少年郎
    2021-02-01 07:13

    The best way to deal with transactions is when they are wrapped properly by a promise library, because transaction logic maps perfectly into the promise event chain, one doesn't have to worry about when to do COMMIT or ROLLBACK, as it happens automatically.

    Here's a complete example of how it works with pg-promise library:

    var pgp = require('pg-promise')(/*options*/);
    
    var cn = "postgres://username:password@host:port/database";
    var db = pgp(cn); // database instance;
    
    db.tx(t => {
        // BEGIN has been executed
        return t.batch([
            t.one("insert into users(name) values($1) returning id", 'John'),
            t.one("insert into users(name) values($1) returning id", 'Mike')
        ]);
    })
        .then(data => {
            // COMMIT has been executed
            console.log(data[0].id); // print id assigned to John;
            console.log(data[1].id); // print id assigned to Mike;
        })
        .catch(error => {
            // ROLLBACK has been executed
            console.log(error); // print why failed;
        });
    

提交回复
热议问题