node.js mysql pool connection with async/ await

后端 未结 6 2091
清酒与你
清酒与你 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:42

    Mates. I don't know why but I tried all the day long but couldn't get it to work. By the help of your comments I tried again and it of course does work.

    db.js:

    const pool = mysql.createPool(config);
    
    exports.getConnection = () => {
        return new Promise((resolve, reject) => {
            pool.getConnection(function (err, connection) {
                if (err) {
                    return reject(err);
                }
                resolve(connection);
            });
        });
    };
    

    someWhereElse.js:

    const db = require('./db');
    
    const wrappingFunction = async () => {
        const connection = await db.getConnection();
        console.log(connection);
    };
    wrappingFunction();
    

提交回复
热议问题