Commit/rollback a knex transaction using async/await

孤者浪人 提交于 2019-11-29 20:27:01

问题


I'm test driving the ES7 async/await proposal using this module to emulate it. I'm trying to make knex.js transactions play well with them, as a starting point.

Example code:

async function transaction() {
  return new Promise(function(resolve, reject){
    knex.transaction(function(err, result){
      if (err) {
        reject(err);
      } else {
        resolve(result);
      }
    });
  });
}

// Start transaction from this call

insert: async (function(db, data) {
 const trx = await(transaction());
 const idUser = await(user.insertData(trx, data));

 return {
    idCidUserstomer: idUser
  }
})

How can I commit() or rollback() if a transaction succeeds or fails?


回答1:


Building off of this Knex Transaction with Promises, it looks like it should be along these lines:

// assume `db` is a knex instance

insert: async (function(db, data) {
  const trx = db.transaction();
  try {
    const idUser = await(user.insertData(trx, data));
    trx.commit();
  } catch (error) {
    trx.rollback();
    throw error;
  }

  return {
    idUser: idUser
  }
})



回答2:


You might be able to achieve this with something similar to this

function createTransaction() {
  return new Promise((resolve) => {
    return knex.transaction(resolve);
  });
}

async function() {
  const trx = await createTransaction();
  ...
  trx.commit();
}



回答3:


You can try this:

async function() {
  await knex.transaction( async (trx) => {
     ...
     trx.commit();
  }
}


来源:https://stackoverflow.com/questions/40581040/commit-rollback-a-knex-transaction-using-async-await

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!