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

Node.js+MySQL使用Promise查询数据库时类属性连接无响应问题求助

问题根因

问题出在this.connection.connect的回调函数的this指向错误:你用普通function声明的回调函数不会继承外层作用域的this,mysql库调用该回调时会将内部的this绑定为连接实例本身/全局对象(取决于运行环境),不再指向你的Request类实例。

你第一个console.log(this.connection)能打印属于巧合:此时回调内的this刚好指向连接实例,你访问的this.connection实际取到的是意外挂载的属性,走到后续代码时访问this.connection.query会直接抛出异常,而你没有给Promise添加catch回调,异常被静默吞掉,所以后续的日志和then回调都不会触发。

修复方案

两种方案任选其一即可:

  1. 将connect的回调换成箭头函数,继承外层作用域的this(指向Request类实例)
const promise = new Promise((resolve, reject) => {
  // 此处this为Request类实例,箭头函数继承外层this
  this.connection.connect((err) => {
    // 箭头函数的this和外层executor的this一致,指向类实例
    console.log(this.connection);
    if (err) return reject(err);
    console.log(this.connection);
    this.connection.query('SELECT * FROM categories;', function (err, rows, fields) {
      if (err) return reject(err);
      resolve(rows);
    });
  });
});
promise.then((result) => console.log(result)).catch(err => console.error('出错:', err));
  1. 在普通函数外层提前缓存类实例的this指向
const promise = new Promise((resolve, reject) => {
  const _this = this; // 提前缓存类实例指向
  this.connection.connect(function(err) {
    console.log(_this.connection);
    if (err) return reject(err);
    console.log(_this.connection);
    _this.connection.query('SELECT * FROM categories;', function (err, rows, fields) {
      if (err) return reject(err);
      resolve(rows);
    });
  });
});
promise.then((result) => console.log(result)).catch(err => console.error('出错:', err));

额外提示:所有异步操作的Promise都要添加catch回调,避免异常被吞导致无法定位问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 00:18:03