Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

320
Views
Can't figure out how to do async functions in NodeJS for MySQL

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

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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:

  1. Give meaningful names to functions and variables;
  2. Learn to connect and retrieve data from db with ORM (my favorite ones Objectionjs + Knexjs);
about 4 years ago · Juan Pablo Isaza Report

0

Use this-

return check_fname;

instead of

return await check_fname;

Also, change your above iteration something like this-

let names = []
let fname = [];
for (let element of names) {
    fname.push(check_name(element));
}
console.log(fname)

hope it will work

about 4 years ago · Juan Pablo Isaza Report

0

You're defining fname inside the loop's scope, then referencing it outside of its scope, rendering it undefined. Try putting the console.log(fname); inside of the for-loop.

On top of that, you're not awaiting your check_name function.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!