Issue
I’m writing some code in JS which requires async function use since I have done some searching on here and it seems async is the way to go for JS.
I am writing a small script for node to trigger a lookup each time a variable is passed through the function. If the variable is in the database it should return as the variable if not then variable would remains unset. I feel my understanding of callbacks and async is lacking. Could anyone point me in the right direction as to what I could be doing wrong.
var mysql = require('mysql');
const util = require('util');
var connection;
const dbConfig = {
host : 'localhost',
user : 'uname',
password : 'password',
database : 'users'
};
async function check_name(check_fname) {
let connection;
try {
connection = await mysql.createConnection(dbConfig);
const result = await connection.query('SELECT fname from users WHERE fname LIKE ' + mysql.escape(check_fname), function (error, results, fields) {
if(results.length > 0){
return await check_fname;
}
}
for (const element of names) {
const fname = check_name(element);
}
console.log(fname); <--- Shows Undefined
Solution
const express = require('express');
const app = express();
const mysql = require('mysql2'); // async/await works only in mysql2, also you need to use mysql2 as dependency (npm i mysql2)
app.use(express.json())
mysql.createConnection({
host : 'localhost',
user : 'uname',
password : 'password',
database : 'users'
}); //keeps always connected to the db
app.get('/user/:name', async (req, res) => {
const name = req.params.name;
const user = await mysql.query(`select fname from users where fname = ${name}`);
console.log(user);
});
app.listen(3000, () => console.log('Server started listening on port 3000');
My recommendations:
- Give meaningful names to functions and variables;
- Learn to connect and retrieve data from db with ORM (my favorite ones Objectionjs + Knexjs);
Answered By – jkalandarov
Answer Checked By – Robin (BugsFixing Admin)