如何使用knex.js使用事务

我有使用knex在数据库表中input多个logging,但我没有任何回应。 我的代码如下:

addApi : (data,CustomerId) => { knex.transaction(function(trx) { knex('books').transacting(trx).insert({name: 'Old Books'}) .then(function(resp) { var id = resp[0]; return someExternalMethod(id, trx); }) .then(trx.commit) .catch(trx.rollback); }) .then(function(resp) { console.log('Transaction complete.'); }) .catch(function(err) { console.error(err); }); } 

从你的问题,我假设交易是成功的,虽然你没有得到一个返回值。

你正在失去你的return someExternalMethod(id, trx); 响应值。 相反,您正在获取.then(trx.commit)的响应值。 在console.log('Transaction complete.');再次做同样的事情console.log('Transaction complete.'); 代码段。

试试这个(未经testing):

  addApi : (data,CustomerId) => { knex.transaction(function(trx) { knex('books').transacting(trx).insert({name: 'Old Books'}) .then(function(resp) { var id = resp[0]; return someExternalMethod(id, trx); }) .then(function(extMethodReturn) { // return the value from the above .then return trx.commit().then(function() { return extMethodReturn; }); }) .catch(trx.rollback); }) .then(function(resp) { console.log('Transaction complete:', resp); return resp; // if you want the value returned. }) .catch(function(err) { console.error(err); }); }