Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

321
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda