Make KnexJS Transactions work with async/await

Posted on

Make KnexJS Transactions work with async/await

I’m trying to make transactions work with async/await and knexjs but to no avail.

The code (snippet is for the sake of shortening the post):

What I’ve tried:

First Try – Error, returns Transaction rejected with non-error

Second Try – Result: Transaction still commits and did not rolled back even though there’s an intentional error.

Solution :

Looks like you are creating transaction, but then you are not sending any queries to it, but send queries to the other database connections in knex’s connection pool.

This is how you should use transactions with knex:

async () {
  try {
    const trxResult = await db.transaction(async (trx) => {
      const queryResult = await trx('table').where(... etc. ...);
      // do some more queries to trx
    });
    console.log("transaction was committed");
  } catch (e) {
    console.log("transaction was rolled back");
  }
}

Also you should try reduce amount of code to minimum before posting problems to stackoverflow. Hiding too much code to snippets doesn’t help at all.

Leave a Reply

Your email address will not be published. Required fields are marked *