How to write promises and connections while executing multiple Mysql queries in Nodejs?

45 Views Asked by At

How can I use multiple queries while constructing promises. Below is the example code of context.

const mysql = require('mysql');
 
const pool = mysql.createPool({
    connectionLimit: 10,    
    password: “yourDBpassword”,
    user: “yourusername”,
    database: “yourDBname”,
    host: “locahost”,
    port: “yourDBport”
 
}); 
SelectAllElements = () =>{
    return new Promise((resolve, reject)=>{
        pool.query('SELECT * FROM DB_table ',  (error, elements)=>{
            if(error){
                return reject(error);
            }
            return resolve(elements);
        });
    });
};

Also, do I need to write db.getconnection everytime I write query functions? Is it possible to end connection without using constructor as it's done below?

const mysql = require( 'mysql' );
class Database {
    constructor( config ) {
        this.connection = mysql.createConnection( config );
    }
    query( sql, args ) {
        return new Promise( ( resolve, reject ) => {
            this.connection.query( sql, args, ( err, rows ) => {
                if ( err )
                    return reject( err );
                resolve( rows );
            } );
        } );
    }
    close() {
        return new Promise( ( resolve, reject ) => {
            this.connection.end( err => {
                if ( err )
                    return reject( err );
                resolve();
            } );
        } );
    }
}
0

There are 0 best solutions below