node.js mysql pool connection with async/ await

后端 未结 6 2100
清酒与你
清酒与你 2020-12-18 04:05

Is there a way to use pool.getConnection() taken from the mysqljs/mysql lib with the async/ await syntax?

The idea is to have a method whic

6条回答
  •  感动是毒
    2020-12-18 04:38

    Just sharing what I've always use in my code:

    //Filename: MySQL.js    
    
    module.exports = {
        connect: function ()
        {
            return new Promise((resolve, reject) => {
    
            let pool = Mysql.createPool({ //require configfile.js or just put connection detail here
                    connectionLimit: config.mysql.connectionLimit,
                    host: config.mysql.host,
                    user: config.mysql.user,
                    password: config.mysql.password,
                    database: config.mysql.database
                });
    
                pool.getConnection((err, connection) =>
                {
                    try
                    {
                        if (connection)
                        {
                            resolve({"status":"success", "data":"MySQL connected.", "con":pool});
                            connection.release();
                        }
                    }
                    catch (err)
                    {
                        reject({"status":"failed", "error":`MySQL error. ${err}`});
                    }
                    resolve({"status":"failed", "error":"Error connecting to MySQL."});
                });
            });
        }
    }
    

    Then whenever you need to call the connection to MySQL

    //Filename: somefile.js
    
    const useMySQL = require('./path/to/MySQL');
    
    module.exports = {
    
        getSomething: function () {
            return new Promise(async (resolve) => {
    
                try
                {
                    let connection = await useMySQL.connect();
                    con = connection.con;
    
                    //Do some query here, then
                    resolve(`Send some result/handle error`);
                }
                catch (err)
                {
                    //Handle error if any, log, etc, and eventually
                    resolve(err);
    
                }
            });
        }
    

    Hope this helps.

提交回复
热议问题