Closed yi-ge closed 7 years ago
Something like this:
var mysql = require('promise-mysql');
var connection;
mysql.createConnection({
host: 'localhost',
user: 'sauron',
password: 'theonetruering',
database: 'mordor'
}).then(function(conn){
connection = conn;
return connection.beginTransaction();
}).then(function(){
return connection.query('INSERT INTO log SET data=?', 'badger');
}).then(function() {
return connection.commit();
}).catch(function(){
return connection.rollback();
});
This should work, but I've not run the code.
Is there any way to do this using async/await syntax? Just curious to see if it is possible
I've not used async/await, but as fast as I know it should just work as async/await just needs calls to return promises. I think it's something like this:
var mysql = require('promise-mysql');
var connection = await mysql.createConnection({
host: 'localhost',
user: 'sauron',
password: 'theonetruering',
database: 'mordor'
})
try {
await connection.beginTransaction();
await connection.query('INSERT INTO log SET data=?', 'badger');
await connection.commit();
} catch () {
await connection.rollback();
}
This code was written on my phone and is untested, but it should give you an idea.
@lukeb-uk Thank you!
thank you.