2016-02-11 40 views
1

我有一个knex事务,我正在执行操作并将事务引用传递给其他方法,在这些方法内我想添加一旦事务完成后将发生的操作。如何在完成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

解决方案很简单,我只是忽略了它:存储事务的承诺,并传递到内部方法,像这样:

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}) 
    } 
} 
相关问题