34
22

More than 5 years have passed since last update.

Node.jsのMySQLでAsync/Awaitする方法

Last updated at Posted at 2018-08-10

Node.jsのMySQLでAsync/Awaitする方法の日本語記事が見当たらなくて苦戦したので備忘録として残しておきます。

以下のように書けばAsync/Awaitがちゃんと効きます。

hoge.js
var mysql = require('mysql');
const util = require('util');
var pool = mysql.createPool({
  connectionLimit: 10,
  host: 'hoge',
  user: 'hoge',
  password: 'hoge',
  database: 'hoge',
})
pool.query = util.promisify(pool.query) // この行がポイント!
try {
  var results = await pool.query('SELECT * FROM myDB')
  pool.end(); // mysqlのコネクションのプロセスを終了させる。(2018-11-07追記)
} catch (err) {
  throw new Error(err)
}
console.log(results)

ちなみにpool.query()はpool.getConnection() + connection.query() + connection.release()のショートカットらしいです。

ではでは。

参考記事
Create a MySQL Database Middleware with Node.js 8 and Async/Await

(2018-11-07追記)
すみません、pool.end();がないとプロセスが終了しないということで追記しました。
@saoshi さん、ありがとうございました。
参考:Node.jsのMySQLでAsync/Awaitしたらプロセスが終わらない

34
22
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
34
22