V
V
vetsmen2018-02-04 23:45:57
JavaScript
vetsmen, 2018-02-04 23:45:57

Mysql transactions using async/await?

There is an example mysql transaction https://github.com/mysqljs/mysql#transactions

the code
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!');
      });
    });
  });
});

I am very confused by callback hell in this case. If I have 5 nested queries, there will be absolutely no readability of the code.
How can this code be rewritten using the familiar asnyc/await?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question