javascriptnode-promisify

Promisify without object instance


We can promisify mysql pool getConnection function if we have already created the pool, like this:

const mysql = require('mysql');
const util = require('util');

const mysqlPool = mysql.createPool(CONFIG);

const getConnectionPm = util.promisify(mysqlPool.getConnection).bind(mysqlPool);

And the usage can be something like:

(async() => {
    const connection = await mysqlPool.getConnectionPm();

});

How can I promisify the mysqlPool.getConnection.query function to use connection variable? To make something like this:

(async() => {
    const connection = await mysqlPool.getConnectionPm();

    const result = await connection.queryPm(SQL_QUERY, SQL_ARGS);
});

The problem is that I don't know how to pass the connection variable to the promisify function. I guess one different way is to create a connection object with getConnectionPm function, then bind the query to that object like what we did to promisify the getConnection itself. But how we can achieve something like the code above?

For example, the code below gives an undefined error:

const getConnectionPm = util.promisify(mysql.createPool.getConnection);

Solution

  • You can change your getConnectionPm, and add a queryPM promisified query method to each connection.

    const getConnectionPm = async () => {
        const conn = await util.promisify(mysqlPool.getConnection).call(mysqlPool);
        conn.queryPm = util.promisify(conn.query).bind(conn);
        return conn;
    }
    

    Then you can query as in your example.

    (async() => {
        const connection = await mysqlPool.getConnectionPm();
        const result = await connection.queryPm(SQL_QUERY, SQL_ARGS);
    });