Commit/rollback a knex transaction using async/await

前端 未结 3 738
猫巷女王i
猫巷女王i 2021-01-03 00:27

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.

Ex

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-03 01:28

    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
      }
    })
    

提交回复
热议问题