Home > Software design >  cant figure out how to do async functions in nodejs for mysql
cant figure out how to do async functions in nodejs for mysql

Time:03-18

im 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

CodePudding user response:

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.

CodePudding user response:

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

  • Related