As part of a small node application I wrote this function that saves something to a database (clearly an async operation) using mysql/mysqljs:
function persist(values) {
getConnection()
.then(connection => {
const {fistName, lastName} = values
const query = mysql.format(
'INSERT INTO names VALUES(NULL, ?, ?)',
[fistName, lastName]
)
return new Promise((resolve, reject) => {
connection.query(query, (err, results, fields) => {
connection.release()
if (err) {
reject(err)
}
resolve([results, fields])
})
})
})
.catch(err => {
console.error(err)
})
}
getConnection
is actually a version of mysqljs/mysql's getConnection function that I promisified using Bluebird.
While this works, it still seems a bit clunky to me because of my use of the Promise constructor. At the moment this is the only solution I was able to come up with due to the special signature of connection.query
(callback second).
Is there a way to further flatten this chain to make it more readable while staying compatible with connection.query
's signature?