Node-mysql2: Transaction code using async await

Created on 19 Sep 2017  路  2Comments  路  Source: sidorares/node-mysql2

How to write the following transaction code using async-await when using pool connection?

/* Begin transaction */
connection.beginTransaction(function(err) {
  if (err) { throw err; }
  connection.query('INSERT INTO names SET name=?', "sameer", function(err, result) {
    if (err) { 
      connection.rollback(function() {
        throw err;
      });
    }

    var log = result.insertId;

    connection.query('INSERT INTO log SET logid=?', log, function(err, result) {
      if (err) { 
        connection.rollback(function() {
          throw err;
        });
      }  
      connection.commit(function(err) {
        if (err) { 
          connection.rollback(function() {
            throw err;
          });
        }
        console.log('Transaction Complete.');
        connection.end();
      });
    });
  });
});
/* End transaction */

Most helpful comment

hi @ashokdey

This is how I think it supposed to work ( if not it's a bug ):

  const conn = await pool.getConnection();
  await conn.beginTransaction();
  await conn.query('INSERT INTO ...', params);
  await conn.commit();
  conn.release();

I'll try to double check this later. Can you try as well?

All 2 comments

hi @ashokdey

This is how I think it supposed to work ( if not it's a bug ):

  const conn = await pool.getConnection();
  await conn.beginTransaction();
  await conn.query('INSERT INTO ...', params);
  await conn.commit();
  conn.release();

I'll try to double check this later. Can you try as well?

hii @sidorares

it's working fine. I was close to it with a bug.

Thanks

Was this page helpful?
0 / 5 - 0 ratings

Related issues

AnyhowStep picture AnyhowStep  路  5Comments

vcorr picture vcorr  路  5Comments

gajus picture gajus  路  3Comments

MHDante picture MHDante  路  4Comments

HugoMuller picture HugoMuller  路  3Comments