Commit / rollback transaction knex using async / wait

I am testing the driving of the ES7 async / await clause using this module to emulate it. I am trying to make knex.js transactions play with them as a starting point.

Code example:

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 the transaction was successful or failed?

+6
source share
3 answers

Building this Knex transaction using Promises is as follows:

 // 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
source

You may 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(); } 
+8
source

You can try this:

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

Source: https://habr.com/ru/post/1012294/


All Articles