for sequential exxecution you need to use async-await
you can write database files like this
const util = require('util')
const mysql = require('mysql')
const pool = mysql.createPool({
connectionLimit: 10,
host: 'localhost',
user: 'root',
password: 'password',
database: 'my_database'
})
// Ping database to check for common exception errors.
pool.getConnection((err, connection) => {
if (err) {
if (err.code === 'PROTOCOL_CONNECTION_LOST') {
console.error('Database connection was closed.')
}
if (err.code === 'ER_CON_COUNT_ERROR') {
console.error('Database has too many connections.')
}
if (err.code === 'ECONNREFUSED') {
console.error('Database connection was refused.')
}
}
if (connection) connection.release()
return
})
// Promisify for Node.js async/await.
pool.query = util.promisify(pool.query)
module.exports = pool
then whenever you can use after import like this.
const db= require('./database')
route.post('/users',async function(){
try{
let result = await db.query('SELECT l.id, l.name FROM country
l ORDER by l.id');
}catch(err){
console.log(err);
}
});
Learn about async-await:
Understanding async/await on NodeJS
https://javascript.info/async-await