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

How can I perform an action on completion of a knex transaction?

本文关键字:完成时 执行 操作 事务 knex      更新时间:2023-09-26

我有一个 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})
  }
}

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

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