Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

322
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda