0

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?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Sven
  • 12,997
  • 27
  • 90
  • 148
  • 1
    This might be a better fit for Code Review Stack Exchange: https://codereview.stackexchange.com/ – Jordan Running Jan 28 '17 at 18:53
  • a) move the promise constructor thing into a separate helper function b) use a custom promisifier in Bluebird – Bergi Jan 28 '17 at 18:58
  • 1
    I very strongly recommend that you never use automatic semicolon insertion. – 4castle Jan 28 '17 at 18:59
  • This code only consists of `getConnection().then().catch()`. There's nothing to flatten as there is no nesting here. The query depends upon the `getConnection()` result so it has to be executed inside the `.then()`. Nothing to flatten there either. – jfriend00 Jan 28 '17 at 19:51
  • For a much simpler `persist()`, try the [disposer pattern](http://stackoverflow.com/a/28915678/3478010). You will end up with more lines of code overall, but amongst them will be a reusable `withDb()` function. – Roamer-1888 Jan 28 '17 at 23:47
  • @Roamer-1888 Wow thank you, this is awesome! My brain is currently melting while trying to understand this, but this seems to be a proper solution! – Sven Jan 29 '17 at 08:55
  • You still need a custom promisification of `connection.query()` but that can be looked after in your `getConnection()` function allowing both `withDb()` and `persist()`. to be very light weight. – Roamer-1888 Jan 29 '17 at 09:59

0 Answers0