2017-10-03 2 views
0

nodejs 8.6, MariaDB, MySQL2/promise 및 클래스를 사용하여 간단하다고 생각한 항목을 시도했습니다. 그러나이 작동하지 않습니다 : 나는이 프로그램을 실행하면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