ang
ang

Reputation: 1581

Proper Javascript promise construction using finally()

I am building out an Express API built with the mssql package.

If I don't call sql.close() then I get the following error:

Error: Global connection already exists. Call sql.close() first.

I'd like to keep the endpoints easy to follow and maintain and like the following pattern using a finally promise pattern.

const sql    = require("mssql")
const config = require("../config")

sql.connect(config.properties).then(pool => {
  return pool.request()
    .execute('chain')
    .then(response => {
      res.send(response['recordsets'][0][0]['response'])
    })
    .catch(err => res.send(err))
    .finally(sql.close())
})

However, this generates the following error:

{ "code": "ENOTOPEN", "name": "ConnectionError" }

The following code works, but it seems a bit clumsy to define sql.close multiple times in the same function.

sql.connect(config.properties).then(pool => {
  return pool.request()
    .execute('chain')
    .then(response => {
      res.send(response['recordsets'][0][0]['response'])
      sql.close()
    })
    .catch(err => {
      res.send(err)
      sql.close()
    })
})

Is there a way to call sql.close as part of the promise chain after either a response or error is sent with res.send?

Upvotes: 0

Views: 48

Answers (1)

Medet Tleukabiluly
Medet Tleukabiluly

Reputation: 11940

.finally accepts function, you passing result of function

sql.connect(config.properties).then(pool => {
  return pool.request()
    .execute('chain')
    .then(response => {
      res.send(response['recordsets'][0][0]['response'])
    })
    .catch(err => res.send(err))
    .finally(() => sql.close()) // FIX HERE
})

Upvotes: 2

Related Questions