如何在完成knex事务时执行操作?

时间:2016-02-11 15:23:21

标签: javascript transactions bluebird knex.js

我有一个knex事务我正在执行操作并将事务引用传递给其他方法,在那些方法中我想添加在事务完成后将发生的操作。

对于蓝鸟承诺的例子,我想要像这样的东西

function a () {
  return knex.transaction(function(trx) {
    trx("blah").select().where("fu","bar")
    .then(function(res) {
       b(trx);
    }).then(trx.commit)
    .catch(trx.rollback); 
  }
}

function b(trx) {
  return trx("blah").select().where("fu","bar")
  .then(function(res) {
      // This is where I want to add code to occur after the trx commits
      trx.then(function(){//Do stuff after trx commits})
  }
}

1 个答案:

答案 0 :(得分:1)

解决方案很简单我只是忽略了它:存储事务承诺并将其传递给内部方法,如下所示:

function a () {
  trxPromise = knex.transaction(function(trx) {
    trx("blah").select().where("fu","bar")
    .then(function(res) {
       b(trxPromise,trx);
    }).then(trx.commit)
    .catch(trx.rollback); 
  }
  return trxPromise;
}

function b(trxPromise,trx) {
  return trx("blah").select().where("fu","bar")
  .then(function(res) {
      // This is where I want to add code to occur after the trx commits
      trxPromise.then(function(){//Do stuff after trx commits})
  }
}