Node.js:如何以最简单的方式将 util.promisify 应用于 mysql 池?

zip*_*per 6 mysql node.js async-await

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);
  });

};
Run Code Online (Sandbox Code Playgroud)

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

Est*_*ask 9

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);
Run Code Online (Sandbox Code Playgroud)

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


Win*_*ers 7

在分享我的例子之前,这里有关于bind 方法async 函数的更多细节。

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()

Run Code Online (Sandbox Code Playgroud)