gpt4 book ai didi

mysql - NodeJS 异步/等待类 mysql/mariadb

转载 作者:行者123 更新时间:2023-11-30 21:52:41 24 4
gpt4 key购买 nike

我尝试了一些我认为使用起来很简单的东西:nodejs 8.6、MariaDB、MySQL2/promise 和类。但它不起作用:

这是一个简单的例子:

const mysql = require('mysql2/promise');

class mySQLClass {
constructor() {
this.mysqlConn = null;
}

async initialize() {
try {
this.mysqlConn = await mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'myschema'
});

console.log('intialize complete - createConnection successful: ');

} catch (err) {
console.log('initialize failed: ' + err);
}
}

async showMeSomeData() {
try {
const [rows, fields] = await this.mysqlConn.execute('select * from information_schema.tables where table_schema = \'information_schema\'');
console.log('data: ' + rows);
} catch (err) {
console.log('showMeSomeData failed: ' + err);
}
}

}

const test = new mySQLClass();

test.initialize();

test.showMeSomeData();

当我运行程序时,它失败了:

showMeSomeData failed: TypeError: Cannot read property 'execute' of null

intialize complete - createConnection successful

因此,似乎 initialize() 在 showMeSomeData() 执行之前未完成。我认为 await 可以让它正常工作吗?

我错过了什么吗?有更好的方法吗?

谢谢

最佳答案

在顶层,异步函数仍然返回一个 promise 。你必须这样做:

const test = new mySQLClass();

test.initialize().then(() => {
test.showMeSomeData();
});

为了让你的代码工作,你必须在你的类中隐藏一个额外的 promise :

async initialize() {
let done, fail;
this.initializing = new Promise((resolve, reject) => {
done = resolve;
fail = reject;
});

try {
this.mysqlConn = await mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'myschema'
});

done();

console.log('intialize complete - createConnection successful: ');

} catch (err) {
console.log('initialize failed: ' + err);
fail();
}
}

async showMeSomeData() {
await this.initializing;
try {
const [rows, fields] = await this.mysqlConn.execute('select * from information_schema.tables where table_schema = \'information_schema\'');
console.log('data: ' + rows);
} catch (err) {
console.log('showMeSomeData failed: ' + err);
}
}

如果你想输出数据,你仍然需要在顶层使用 promises,但你的 console.logs 至少会在带内发生。

关于mysql - NodeJS 异步/等待类 mysql/mariadb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46554371/

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