0

I would like to know how to pass the value from mysql query to a variable out of the function:

mydb.js

const mysql = require('mysql');

const con = mysql.createConnection({
    host: process.env.HOST,
    user: process.env.USER,
    password: process.env.PASSWORD,
    database: process.env.DATABASE
});

con.connect(function(err) {
    if (err) throw err;      
});


async function loadDataInside(callback){
     
    con.query("SELECT content FROM whatsappauth Where id = 1", function (err, result, fields) {
        if (err) throw err;                                
        return callback(result[0].content);               
    });  

}

let ff;

loadDataInside(async function(res){
    ff = await res;
    
});

console.log('++',ff,'gg');

The result is:

++ undefined gg

Why inside the function 'ff' have the right value and out it become 'undefined' ? How should I solve this problem?

1 Answers1

0

Because this is how it execute

let ff;
console.log('++',ff,'gg'); So here you are getting undefined
loadDataInside(async function(res){
    ff = await res;
    
});

You will have to write the code inside the callback function, Or it is better to use promise, Please do not mix the promise and callback.

Indraraj26
  • 1,726
  • 1
  • 14
  • 29