1

connection.js

let mysql = require('mysql2'); let pool = mysql.createPool({ host:'localhost', user: 'root', database: '', password: '', connectionTimeout: 10000 }).promise() pool.getConnection(function(err, connection) { console.log('connected to database') }); pool.on('error', function(err) { console.log(err.code); }); module.exports = { getConnection: () => { return pool.getConnection() } }; 

other_file.js

router.get('/', async (req, res) => { const conn = await connWrapper.getConnection(); let [courses] = await conn.execute('SELECT * FROM courses'); courses = courses; //database stuff here and page rendering etc }); 

If I load the page for the first time, it works, however after just a few seconds it stops working and the page won't load anymore, that even if I remove connectionTimeout. Also, how come that I do not receive logs from pool.getConnection and pool.on('error'). There aren't logs in the console whatsoever.

1 Answer 1

2

you need to release connection back to the pool after you no longer need it. Default pool config id connectionLimit: 10, queueLimit: 0, so your first 10 requests use all available connections in the pool and later requests are stuck at await connWrapper.getConnection(); line waiting for previous connections to be available.

Example returning connections to the pool:

router.get('/', async (req, res) => { const conn = await connWrapper.getConnection(); try { const [courses] = await conn.execute('SELECT * FROM courses'); //... } finally { conn.release(); // no need to await here, .release() is sync call } }); 

Or you can just use .execute() helper on a pool:

// add this to connection.js: // execute: (...args) => pool.execute(...args) router.get('/', async (req, res) => { const [courses] = await connWrapper.execute('SELECT * FROM courses'); // ... }); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.