gpt4 book ai didi

javascript - 无法读取未定义的 mysql 的属性 'typeCast'

转载 作者:可可西里 更新时间:2023-11-01 07:55:45 24 4
gpt4 key购买 nike

我有代码:

import { createConnection } from 'mysql';
import { promisify } from 'util';

export default class Database {
static instance: Database;

query;
db;

constructor(user, password, database, host) {
Database.instance = this;

this.db = createConnection({ user, password, database, host });
this.db.connect();
this.query = promisify(this.db.query);
}

async getUser(id: number, filter: string = null) {
return this.query('SELECT * FROM users WHERE id = ' + id)
.then((err, res, fields) => {
return res[0];
});
}
}

以及将 id 传递给 getUser 的快速路由。

当这段代码被执行时,我得到了这个堆栈。

(node:16544) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:16544) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'typeCast' of undefined
at Database.query (<project>\node_modules\mysql\lib\Connection.js:199:34)
at Database.query (internal/util.js:232:30)
at Database.getUser (<project>\lib\structures\Database.js:13:21)
at get (<project>\lib\api\routes\user.js:5:33)
at Layer.handle [as handle_request] (<project>\node_modules\express\lib\router\layer.js:95:5)
at next (<project>\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (<project>\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (<project>\node_modules\express\lib\router\layer.js:95:5)
at <project>\node_modules\express\lib\router\index.js:281:22
at param (<project>\node_modules\express\lib\router\index.js:354:14)
(node:16544) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 6)

我该如何解决?

最佳答案

对于同一个问题,我找到了不同的解决方案。我没有用这个测试你的代码,但是查看 mysql 模块的源代码,在我的例子中 this 不再正确。将 query 绑定(bind)到 db 对象为我修复了它。在您的情况下,它看起来像这样:
this.query = promisify(this.db.query.bind(this.db));

关于javascript - 无法读取未定义的 mysql 的属性 'typeCast',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48510876/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com