ํ๋ก์ ํธ ์งํํ๋ฉด์ ๋ค๋ฅธ ํจ์๋ค์ ๋ค async/await์ผ๋ก ๋น๋๊ธฐ์ฒ๋ฆฌ๋ฅผ ํ์๋๋ฐ, ์ฟผ๋ฆฌ๋ฌธ์ ๊ทธ๋ ๊ฒ ํ์ง ์๊ณ ์ฝ๋ฐฑ์ง์ฅ์ ๊ตฌํํ๊ณ ์์๋ค. ๋๋ฌด ๊ธฐ๊ณ์ ์ผ๋ก ์ฝ๋ฉํ์ง ์์๋ ์ถ์ ์๊ฐ์ด ๋ค์๋ค.
version 1
const sql_team_no = 'select max(team_no) as newTeam from travel_with;'
conn.query(sql_team_no, async function(err, data){
if(err){
console.log(err)
return res.send('failed to get new team number')
}
else{
~~~
const sql = 'insert into travel_with set ?;'
conn.query(sql, params, function(err, data){
if(err){
console.log(err)
return res.status(statusCode.OK).send(util.fail(statusCode.INTERNAL_SERVER_ERROR, responseMessage.QUERY_ERROR,
"failed to store new plan (existed user in travel_with table)"))
}else{
์์ ๊ฐ์ ๊ตฌ์กฐ์ ๋ฌธ์ ์ ์ด ๋ฌด์์ด๋ผ๊ณ ์๊ฐํ๋...
sql์ ์คํํ๊ณ ๋ง์ฝ์ err๊ฐ ๋๋ค๋ฉด err์ ํด๋นํ๋ response๋ฅผ ๋ฆฌํดํ๋ค.
๊ทธ๋ ๊ฒ ๋๋ฉด ํด๋น ํจ์์์ ๋น ์ ธ๋์ค๊ฒ ๋๋๋ฐ, ๊ทธ๋ ๊ฒ ๋น ์ ธ๋์ค๋ฉด ์ด๋๋ก ๊ฐ๋.
๋ฐ๋ก ์์ ๋ณด๋ฉด sql_team_no ์ฟผ๋ฆฌ๋ฅผ ์คํํ๋ ํจ์๋ก ๊ฐ๋ค.
๊ทธ๋ฌ๋ฉด? ๋ฆฌํด์ ๋๋ฒํ๋ค
๊ทธ๋ ๊ฒ ๋๋ฉด Error: Can't render headers after they are sent to the client.
์ ๊ฐ์ ์๋ฒ ๊ฐ๋ฐ์๋ค์ด ๋ง์ด ๊ฒช๋ ์๋ฌ๋ฅผ ๋ณด๊ฒ ๋๋ค.
๋๋ ์ฒ์์ ๋ด๊ฐ try catch๋ฅผ ์ ๋ชป ์ดํดํ๊ณ ์๋...? ์๋ฌ๊ฐ ์๊ธฐ๋ฉด catch๋ก ๊ฐ์ผ ํ๋๋ฐ if(err) ์ฌ๊ธฐ์ ๊ฑธ๋ ค์ response๋ฅผ ๋๋ฒ ํด์ ์ค๋ฅ๊ฐ ์๊ธฐ๋๊ฑด๊ฐ??
์๋๋ค... ๊ทธ๋ฅ ์์ ๋งํ๊ฒ์ด ์๋ชป์ด์๋ค. ํจ์๋ฅผ ๋์๋ ๋ ํจ์์์ ๊ฑธ๋ฆฌ๊ธฐ ๋๋ฌธ์...
๊ฒฐ๊ตญ ๋น๋๊ธฐ์ฒ๋ฆฌ๋ฅผ ๋ด๊ฐ ๋ชปํ๊ฒ์ด์๋ค.
๊ทธ๋ผ ์ด๋ป๊ฒ ํด์ผํ ๊น
version 2
const connection = await mysql.createConnection(conn.db_info);
const locationResult = await getLocation(latlng)
const country_code = locationResult.data.plus_code.global_code // country code ex)87G8M376+PJ - koera
const country = country_code.slice(0,4);
const sql = `select * from travel_with where region_info like '${country}%' and isfinished = '0';`
const result = await connection.query(sql)
AWS.config.update(userConfig.aws_iam_info);
const docClient = new AWS.DynamoDB.DocumentClient();
์์ ๊ฐ์ด ์ฟผ๋ฆฌ๋ฌธ์ async/await ์ผ๋ก ์ฒ๋ฆฌ๋ฅผ ํด์ผ response๋ฅผ ํด๋ ๋ ๋ค์ ํจ์์์ ๊ฐํ๋ ๊ทธ๋ฐ ๋ถ์์ฌ๊ฐ ์ผ์ด๋์ง ์๋๋ค.
์ด? ๋๋ nodejs ์์ mysql ๋ชจ๋์ ์ฌ์ฉํ๋ ค๊ณ ํด๋ async/await ์ฒ๋ฆฌ๊ฐ ์๋๋๋ฐ...? ๋ผ๊ณ ์๊ฐํ๋ ๊ฒฝ์ฐ๊ฐ ์์ ์ ์๋ค. ๋ ๋ํ ๊ธฐ์กด์ ์ฌ์ฉํ๋ ๋ชจ๋๋ก๋ async/await๋ฅผ ์ฒ๋ฆฌ ํ์ง ๋ชปํด์ ๋ญ์ง? ๋ผ๋ ์๊ฐ์ ํ์๋ค.
๐ mysql2 ๋ชจ๋์ ์ฌ์ฉํด์ผ ํ๋ค.
์ฆ,mysql
์ ์ฝ๋ฐฑ๊ธฐ๋ฐ์ด๊ณ ,mysql2
์ promise๊ฐ์ฒด ์ฌ์ฉ์ด ๊ฐ๋ฅํ๋ค.
mysql์ ์ฝ๋ฐฑ๊ธฐ๋ฐ์ด๊ธฐ ๋๋ฌธ์ promise๊ฐ์ฒด๋ฅผ ์ฌ์ฉํ๊ธฐ ์ํด์๋ promise-mysql
๋ชจ๋์ ์ฌ์ฉํด์ผ ํ๋ค. ํ์ง๋ง mysql2์ ๋ค๋ฅธ ๋ชจ๋ ํ์์์ด promise ๊ฐ์ฒด ์ฌ์ฉ์ด ๊ฐ๋ฅํ๋ค.
๊ทธ๋ฌํ๋ค... ๊ทธ๋์ ๊ฒฐ๊ตญ์ mysql2๋ฅผ ํตํด์ promise๊ฐ์ฒด๋ฅผ ์ฌ์ฉํ์ฌ ์ค๋ฅ๋ฅผ ํด๊ฒฐํ ์ ์์๋ค. ์์ผ๋ก mysql ๋ชจ๋์ ์ฌ์ฉํ์ง ์์๋ฏ...^^ ๋ฌด์กฐ๊ฑด mysql2
๐