Lord Elrond
Lord Elrond

Reputation: 16002

How to end DB connection using Mysql2 Promise?

The following code works as expected, except that I can't seem to figure out how to call con.end();

db.js:

const
mysql = require('mysql2/promise'),
config = {
  host: 'localhost',
  port: 3306,
  user: 'root',
  password: '',
  database: 'webhooks'
};

module.exports = async () => {
  const
  con = await mysql.createConnection(config),
  sql = 'SELECT * FROM table',
  data = [];

  let [rows, fields] = await con.execute(sql);

  return rows;
}

app.js:

const test = require('./db.js');

test.then(console.log);

I've tried adding con.end(); right before return rows;, and I've also tried various combinations of test.then(...).catch(...).then(() => con.end()); but no results.

What am I missing here?

Upvotes: 1

Views: 705

Answers (1)

ambianBeing
ambianBeing

Reputation: 3529

In the async exports function since all async operations (connection, fetch) are being awaited. The con.end() should ideally be an async operation and can be simply awaited as the results are fetched and resolved just before.

module.exports = async () => {
  const
  con = await mysql.createConnection(config),
  sql = 'SELECT * FROM table',
  data = [];

  let [rows, fields] = await con.execute(sql);
  await con.end();
  return rows;
}

An then in app.js get rows that were returned:

const test = require('./db.js');

test.then(rowsResults => console.log(rowsResults)); //only rows were returned
  • con object can also be sent as part of returned promise along with rows and subsequently can be closed in thenable of test but that would seem more verbose in this case.

Upvotes: 2

Related Questions