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