6

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?

nicholaswmin
  • 21,686
  • 15
  • 91
  • 167

3 Answers3

8

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();
}
Alex Beauchemin
  • 1,072
  • 1
  • 17
  • 24
2

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
  }
})
Community
  • 1
  • 1
Lance
  • 75,200
  • 93
  • 289
  • 503
  • 1 note here - For some strange reason, putting the `return { idCustomer: idCustomer}` part inside the `try` block makes it tick just fine, otherwise it hangs, as in the part below the `try..catch` doesn't run – nicholaswmin Nov 14 '16 at 02:52
  • Try using `await` on trx.commit and trx.rollback, otherwise not too sure. – Lance Nov 14 '16 at 03:00
  • `Try using await on trx.commit/trx.rollback` - didn't work but I'll dig around and post a comment here. – nicholaswmin Nov 14 '16 at 03:03
  • @NicholasKyriakides did you come up with any answer to the hanging issue? – serkan Jan 03 '17 at 08:20
  • @serkandemirel0420 Unfortunately, no - if you figure it out I'd be happy to know though – nicholaswmin Jan 03 '17 at 09:25
1

You can try this:

async function() {
  await knex.transaction( async (trx) => {
     ...
     trx.commit();
  }
}
Christian
  • 819
  • 1
  • 8
  • 23
  • This is wrong. You should not call commit inside of .transaction. it will automatically do that for you when the promise resolves. – Tim Oct 13 '22 at 01:42