teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

createConnectionの使い方の変化に追従出来るよう修正

2021/11/12 06:16

投稿

miyabi-sun
miyabi-sun

スコア21461

answer CHANGED
@@ -81,7 +81,8 @@
81
81
  // mysql2にはPromise動作モードというのがある
82
82
  const mysql = require("mysql2/promise");
83
83
 
84
- // ここは基本的にこのままで構わない
84
+ // ここはこのままで構わない
85
+ // ただし返り値がPromiseのインスタンスになっており、一度thenを叩いて本物のコネクションを取り出す必要がある
85
86
  const connection = mysql.createConnection({
86
87
  host: 'localhost',
87
88
  user: 'root',
@@ -92,17 +93,18 @@
92
93
  app.post('/select', (req, res) => {
93
94
  const variables = {};
94
95
 
96
+ // connection.thenを基点に展開する
95
- connection.query(
97
+ connection.then(c => c.query(
96
98
  'SELECT date, temperature, humidity FROM data WHERE device = ? ORDER BY date ASC;',
97
99
  [req.body.device]
98
- ).then(results => {
100
+ )).then(results => {
99
101
  console.log(results);
100
102
  variables.items = results;
101
103
 
102
- return connection.query(
104
+ return connection.then(c => c.query(
103
105
  'SELECT * FROM data where date=(select max(date) from data where device = ?);',
104
106
  [req.body.device]
105
- );
107
+ ));
106
108
  }).then(results => {
107
109
  console.log(results);
108
110
  variables.news = results;
@@ -135,11 +137,12 @@
135
137
  // 普通のアロー関数の前にasyncというワードを付与するだけ
136
138
  app.post('/select', async (req, res) => {
137
139
  // awaitを使うとPromise.then(val => {})を実行してvalを取り出すコードに変換される
140
+ const c = await connection;
138
- const items = await connection.query(
141
+ const items = await c.query(
139
142
  'SELECT date, temperature, humidity FROM data WHERE device = ? ORDER BY date ASC;',
140
143
  [req.body.device]
141
144
  );
142
- const news = await connection.query(
145
+ const news = await c.query(
143
146
  'SELECT * FROM data where date=(select max(date) from data where device = ?);',
144
147
  [req.body.device]
145
148
  );
@@ -162,6 +165,7 @@
162
165
  app.post('/select', async (req, res) => {
163
166
  const val = {};
164
167
  try {
168
+ const c = await connection;
165
169
  const items = await connection.query(
166
170
  'SELECT date, temperature, humidity FROM data WHERE device = ? ORDER BY date ASC;',
167
171
  [req.body.device]