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
  • 19,740
  • 13
  • 80
  • 155

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
  • 962
  • 1
  • 15
  • 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
  • 69,908
  • 82
  • 257
  • 454
  • 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
2

You can try this:

async function() {
  await knex.transaction( async (trx) => {
     ...
     trx.commit();
  }
}
Christian
  • 729
  • 7
  • 23