7

I saw another thread and and the post Create a MySQL Database Middleware with Node.js 8 and Async/Await, but right now I just want to use the util.promisify in the most simplest and straight-forward way that I can think, applying it to mysql connection-pool. Regarding the Node.js documentation, bellow is my code snipet:

exports.genAdminCfg = function (app) {
  let sql = 'SELECT * FROM nav_tree;';

  let pool = require('mysql').createPool({
    host: 'localhost',
    user: 'root',
    password: 'mysql',
    database: 'n4_ctrl',
    connectionLimit: 4,
    multipleStatements: true
  });

  /* --- Works fine without "promisify":
   pool.query(sql, function (err, rows) {
     if (err) {
       console.log(err);
       return err;
     } else {
       app.locals.adminCfg = genCfg(rows);
       app.locals.adminCfg.dbConnectionPool = pool;
     }
   });
  */

  /* --- Does not worke with "promisify":
     TypeError: Cannot read property 'connectionConfig' of undefined
       at Pool.query (/usr/home/zipper/node/n4.live/node_modules/mysql/lib/Pool.js:194:33)
  */
  require('util').promisify(pool.query)(sql).then(function (rows) {
    app.locals.adminCfg = genCfg(rows);
    app.locals.adminCfg.dbConnectionPool = pool;
  }, function (error) {
    console.log(error);
  });

};

The code I commented-out works fine without promisify. But the similar code next to it with promisify does not work and shows TypeError: Cannot read property 'connectionConfig' of undefined. What's wrong with the code?

node version = v8.1.4

zipper
  • 377
  • 1
  • 5
  • 18

2 Answers2

14

It always should be expected that a method relies on the context, unless proven otherwise.

Since pool.query is a method, it should be bound to correct context:

const query = promisify(pool.query).bind(pool);

This may be unneeded because there are promise-based alternatives for most popular libraries that could make use of promises, including mysql.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • Thanks @estus, `promisify(pool.query).bind(pool)(sql)` works ;). I need to study more on the binding mechanism. – zipper Feb 17 '19 at 06:39
10

Before sharing my example, here are greater details about bind method and async function.

const mysql = require('mysql')
const { promisify } = require('util')

const databaseConfig = {
  connectionLimit : 10,
  host: process.env.DB_HOST,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME
}

const pool = mysql.createPool(databaseConfig)
const promiseQuery = promisify(pool.query).bind(pool)
const promisePoolEnd = promisify(pool.end).bind(pool)

const query = `select * from mock_table limit 1;`
const result = await promiseQuery(query) // use in async function

promisePoolEnd()

Winters Huang
  • 761
  • 10
  • 18