8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Node.jsのMySQLでAsync/Awaitしたらプロセスが終わらない

Last updated at Posted at 2018-11-07

Node.jsのMySQLでAsync/Awaitしたら、データの取得はうまくいったけどプロセスがいつもまで経っても終わらなかったのでメモ。

Node.jsのMySQLでAsync/Awaitについてはこちらの記事を参考にさせていただきました。
Node.jsのMySQLでAsync/Awaitする方法

プロセスが終わらないコード

const mysql = require('mysql');
const util = require('util');


// 取得
async function findRecord(id) {
  var pool = mysql.createPool({
    host: ' *** ',
    user: ' *** ',
    password: '***',
    database: ' *** ',
  })
  pool.query = util.promisify(pool.query)
  try {
    var records = await pool.query('SELECT * FROM xxxx WHERE id = ' + id);
    return records[0];
  } catch (err) {
    throw new Error(err)
  }
}


(async () => {
  const record = await findRecord(1);
  console.log(record);
})();

なぜプロセスが終わらないのか

mysqlのコネクションが残ったままになっていると仮定し、コネクションを終了させたところ、解決しました。

完成したコード

const mysql = require('mysql');
const util = require('util');


// 取得
async function findRecord(id) {
  var pool = mysql.createPool({
    host: ' *** ',
    user: ' *** ',
    password: '***',
    database: ' *** ',
  })
  pool.query = util.promisify(pool.query)
  try {
    var records = await pool.query('SELECT * FROM xxxx WHERE id = ' + id);
    pool.end();// ←これです
    return records[0];
  } catch (err) {
    throw new Error(err)
  }
}


(async () => {
  const record = await findRecord(id);
  console.log(record);
})();
8
6
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
8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?