V
V
vetsmen2018-03-01 05:03:45
JavaScript
vetsmen, 2018-03-01 05:03:45

How to use mysql transactions along with async/await?

Good day. There is a mysql library for node.js.
Here is the code for mysql transactions:

spoiler
connection.beginTransaction(function(err) {
  if (err) { throw err; }
  connection.query('INSERT INTO posts SET title=?', title, function (error, results, fields) {
    if (error) {
      return connection.rollback(function() {
        throw error;
      });
    }

    var log = 'Post ' + results.insertId + ' added';

    connection.query('INSERT INTO log SET data=?', log, function (error, results, fields) {
      if (error) {
        return connection.rollback(function() {
          throw error;
        });
      }
      connection.commit(function(err) {
        if (err) {
          return connection.rollback(function() {
            throw err;
          });
        }
        console.log('success!');
      });
    });
  });
});

As you can see, this is cb hell. How can this code be rewritten using async/await?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladlen Hellsite, 2018-03-01
@vetsmen

If I understand everything correctly, then:

const { promisify } = require('util');

/* ... */

const query = promisify(connection.query).bind(connection);
const commit = promisify(connection.commit).bind(connection);
const rollback = promisify(connection.rollback).bind(connection);
const beginTransaction = promisify(connection.beginTransaction).bind(connection);

/* ... */

async function run(title) {
  try {
    await beginTransaction();

    const { insertId } = await query('INSERT INTO posts SET title=?', title);

    const log = `Post ${insertId} added`;

    await query('INSERT INTO log SET data=?', log);

    await commit();

    console.log('Success!');
  } catch (e) {
    await rollback();
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question