NodeJS ,mysql2 +连接池,承诺,mysql查询通用函数

gkn4icbw  于 2022-12-26  发布在  Node.js
关注(0)|答案(1)|浏览(152)

我正在使用:mysql2我想创建通用查询功能模块,我将在任何其他模块中使用。
我的app.js

//globals include
options          = require('./options'); //DB settings
db               = require('./lib/db'); //DB Driver
async function init(){
var  result = await db.query("SELECT * FROM log");
console.log(result);

}

init();

我的db.js

const { resolve } = require("bluebird");
const DataBase = require("mysql2"); // import the class

const pool = DataBase.createPool({
    connectionLimit: 50,
    host: options.db_host,
    user: options.db_login,
    database: options.db_name,
    password: options.db_password
}).promise();


module.exports.query = async function (sql) {
   const connection = await pool.getConnection();

   return connection.query(sql)
    .then(result =>{
      //console.log(result[0]);
      return result[0];
    })
    .catch(err =>{
      console.log(err);
    })
    .then(() => connection.release());
    

}

当我启动app.js时,我得到:

2022-12-23T01:20:49.362Z
 undefined

但如果我在db.js中使用这段代码,我看到,代码工作正常(他在DB的控制台日志中显示行):

module.exports.query = async function (sql) {
   const connection = await pool.getConnection();

   return connection.query(sql)
    .then(result =>{
      console.log(result[0]);
      //return result[0];
    })
    .catch(err =>{
      console.log(err);
    })
    .then(() => connection.release());
    

}
vuktfyat

vuktfyat1#

您没有在所有.then()链上返回connection.query的结果。是的,承诺链比基于回调的API更好,但如果您有承诺,请使用async/await
这是我从你的代码中创建的一个小示例代码。它使用了我的MySQL数据库,所以查询不是针对你的表。

使用承诺链

数据库. js

import config from './config.js';
import DataBase from 'mysql2';

const pool = DataBase.createPool(config.db).promise();

const query = async function (sql) {
    const conn = await pool.getConnection();
    return conn.query(sql)
        .then(result => {
            console.log('Query results: %o', result);
            return result;
        })
        .then((r) => {
            conn.release();
            return r;
        });
};

export default query;

索引. js

import query from "./db.js"

const result = await query('select * from Users');
console.log('Result: %o', result);

如您所见,您需要从第一个then()返回,以便在第二个then()中获得结果,然后,从第二个then()返回。

使用异步/等待

数据库. js

import config from './config.js';
import DataBase from 'mysql2';

const pool = DataBase.createPool(config.db).promise();

const query = async function (sql) {
    const conn = await pool.getConnection();
    const result = await conn.query(sql);
    conn.release();
    return result;
};

export default query;

简单多了,对吧?
为了完整起见,我的config.jswj-config的一个实现。

更新

抱歉,我忘了告诉您,我是在ES模块而不是CommonJS模块中编写此代码的,这是有一个重要原因的:我可以在任何地方使用await。我不需要init()函数。让我们规范化在ES模块中编写服务器端代码。:-)

相关问题