【问题标题】:NodeJS async/await class mysql/mariadbNodeJS 异步/等待类 mysql/mariadb
【发布时间】:2017-10-04 13:00:14
【问题描述】:

我尝试了一些我认为很简单的东西: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 失败:TypeError:无法读取 null 的属性“执行”

初始化完成 - createConnection 成功

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

我错过了什么吗? 有没有更好的方法来做到这一点?

谢谢

【问题讨论】:

    标签: mysql node.js class asynchronous async-await


    【解决方案1】:

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

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

    要让你的代码工作,你必须在你的类中隐藏一个额外的承诺:

    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);
        }
    }
    

    如果您想获取数据,您仍然必须在顶层使用 Promise,但您的 console.logs 至少会在带内发生。

    【讨论】:

    • 谢谢。这解决了这个问题。它确实让我质疑使用 async/await 与仅使用 Promise 或回调相比的价值。
    猜你喜欢
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    • 2019-07-20
    • 2021-07-08
    • 2018-02-08
    • 2020-03-31
    • 2019-06-30
    • 2019-08-08
    相关资源
    最近更新 更多