Answer the question
In order to leave comments, you need to log in
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:
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!');
});
});
});
});
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question