You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用mysql2/promise连接池时回调函数报错问题求助

问题:mysql2/promise连接池报错"Callback function is not available with promise clients"

我基于Node.js+Express开发REST API,使用mysql2/promise创建数据库连接池,查询vehicles表时触发错误,错误提示:

Error: Callback function is not available with promise clients.

路由代码

import express from 'express';
import mysql2 from 'mysql2';
import multer from 'multer';
import path from 'path';
import dbPool from './db.js';
import dotenv from 'dotenv';
dotenv.config()

const route = express.Router();

route.get("/", (req, res) => {
    dbPool.query("SELECT * FROM vehicles", (err, result) => {
        if (err) {
            console.error("Loading Failure:", err);
            res.status(500).send("Loading Failure");
        } else {
            res.send(result);
        }
    });
})

连接池配置代码

import mysql from 'mysql2/promise';
import dotenv from 'dotenv';

dotenv.config();

const dbPool = mysql.createPool({
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    waitForConnections: true,
    connectionLimit: 20, // 根据需求调整
    queueLimit: 0,
})

dbPool.getConnection((err, connect) => {
    if (err) {
        console.log(err)
    } else if (connect) {
        console.log("Pool Connected")
    }
    connect.release()
})

export default dbPool;

完整错误堆栈

Error: Callback function is not available with promise clients.
    at PromisePool.query (C:\Users\gwala\carRental\rental_api\node_modules\mysql2\promise.js:358:13)
    at file:///C:/Users/gwala/carRental/rental_api/routes/vehicles.js:12:12
    at Layer.handle [as handle_request] (C:\Users\gwala\carRental\rental_api\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\gwala\carRental\rental_api\node_modules\express\lib\router\route.js:144:13)
    at Route.dispatch (C:\Users\gwala\carRental\rental_api\node_modules\express\lib\router\route.js:114:3)
    at Layer.handle [as handle_request] (C:\Users\gwala\carRental\rental_api\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\gwala\carRental\rental_api\node_modules\express\lib\router\index.js:284:15
    at Function.process_params (C:\Users\gwala\carRental\rental_api\node_modules\express\lib\router\index.js:346:12)  
    at next (C:\Users\gwala\carRental\rental_api\node_modules\express\lib\router\index.js:280:10)
    at Function.handle (C:\Users\gwala\carRental\rental_api\node_modules\express\lib\router\index.js:175:3)

解决方法

错误根源

你使用的是mysql2/promise提供的Promise风格连接池,但代码中混用了回调函数写法——Promise版本的API不支持传入回调参数,必须用async/await或.then()/.catch()来处理异步操作。

1. 修正路由代码(使用async/await)

将路由处理函数改为异步函数,用try/catch捕获查询错误:

import express from 'express';
import multer from 'multer';
import path from 'path';
import dbPool from './db.js';
import dotenv from 'dotenv';
dotenv.config()

const route = express.Router();

route.get("/", async (req, res) => {
    try {
        // mysql2/promise的query返回数组,第一个元素是查询结果
        const [result] = await dbPool.query("SELECT * FROM vehicles");
        res.send(result);
    } catch (err) {
        console.error("Loading Failure:", err);
        res.status(500).send("Loading Failure");
    }
})

export default route;

2. 修正连接池初始化代码(改用Promise风格)

原代码中getConnection用了回调,同样需要改成Promise写法,避免潜在错误:

import mysql from 'mysql2/promise';
import dotenv from 'dotenv';

dotenv.config();

const dbPool = mysql.createPool({
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    waitForConnections: true,
    connectionLimit: 20, // 根据需求调整
    queueLimit: 0,
})

// 用立即执行函数+async/await测试连接池
(async () => {
    try {
        const connect = await dbPool.getConnection();
        console.log("Pool Connected");
        connect.release();
    } catch (err) {
        console.error("连接池初始化失败:", err);
    }
})();

export default dbPool;

注意事项

  • mysql2/promise的query方法返回一个包含结果集和字段元数据的数组,通常我们只需要第一个元素,所以用数组解构const [result] = ...获取。
  • Express支持异步路由处理函数,只要标记为async,框架会自动处理Promise的resolve/reject状态。

内容的提问来源于stack exchange,提问作者CodeMHT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 13:02:33