2017-10-03 8 views
0

私はnodejs 8.6、MariaDB、MySQL2/promise、およびclassesを使って簡単なことを考えました。しかし、それは動作しません:私はプログラムを実行するとNodeJS async/await class mysql/mariadb

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

だから、それは(その初期表示されます)ではありませんshowMeSomeData()が実行される前に完了します。私はこれが正しく動作するのを待っていると思った?

何か不足していますか? これを行うより良い方法はありますか?

おかげでトップレベルに

答えて

0

は、非同期機能はまだ約束を返します。

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

あなたはまだ上部にある約束を使用する必要があります:あなたは、クラス内の余分な約束を非表示にする必要があるだろう、

const test = new mySQLClass(); 

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

をあなたのコードが動作するように取得するには:あなたは何をする必要がありますあなたがデータを取り出そうとしているなら、あなたのconsole.logsは少なくともインバンドで起こるでしょう。

+0

ありがとうございました。これで問題は解決しました。それは私に、async/awaitを使用することの価値と、約束やコールバックを使用することの価値に疑問を投げかけています。 – nwrbs