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

标签 mysql node.js class asynchronous async-await

我尝试了一些我认为使用起来很简单的东西: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/

相关文章:

c++ - 带有类参数的 std::thread 初始化导致类对象被多次复制

php - 使用 MySQL PHP 更改 VARCHAR?

php - Android - 如何使用 PHP 从 MySQL 数据库获取响应?

node.js - 如何在快速 route 引用模块

c++ - 在析构函数中释放内存时出现段错误

python - 如何从类中的方法获取一个值而不重新计算?

php - 如何每 30 天使用触发器更新一次表?

mysql - 管理逻辑约束以处理 mySQL 数据库插入中的并发性

node.js - 同步 sequelize.sync() 还是不同的方式?

JSON.stringify 不适用于 NodeJs 中的 mongoose 对象