I have a .js file that calls an external .js file that runs the following code:
const sql = require('../../node_modules/mysql');
module.exports =
{
connect_to_db: function (sql_query)
{
let con = sql.createConnection({
host: "localhost",
user: config.server_username,
password: config.server_password,
database: config.database_name
});
con.connect((err)=> {
if (err){
console.log("Problem connecting to the DB!");
return;
}
console.log("Connected to the DB!");
});
con.query(sql_query, (err, result) => {
if (err) throw err;
console.log('Data received from the DB');
console.log(result);
return result;
});
con.end((err) => {});
}
};
Which is run like:
const connect_to_DB = require('DB_Connection');
let sql_query = "SELECT * FROM table";
database_results.push(connect_to_DB.connect_to_db(sql_query));
console.log(database_results);
however this results in the code finishing before the sql query comes back with a result (data removed):
[ undefined ]
Connected to the DB!
Data received from the DB
[ RowDataPacket {
mail_id: ,
from: ,
to: ',
subject: ,
message: ,
date:,
read_date: } ]
Process finished with exit code 0
It looks like the push of the result is coming back as undefined as there is nothing to push at the point it does this. However I want it to wait until the response from the query comes back before it continues.
I was thinking of a promise perhaps but not sure if that would work something like:
const sql = require('../../node_modules/mysql');
module.exports =
{
connect_to_db: function (sql_query)
{
return new Promise((resolve, reject) => {
(async () => {
let con = sql.createConnection({
host: "localhost",
user: config.server_username,
password: config.server_password,
database: config.database_name
});
con.connect((err)=> {
if (err){
console.log("Problem connecting to the DB!");
return;
}
console.log("Connected to the DB!");
});
con.query(sql_query, (err, result) => {
if (err) throw err;
console.log('Data received from the DB');
console.log(result);
resolve();
return result;
});
con.end((err) => {});
})();
});
}
};
but when I run this I get this back:
[ Promise { <pending> } ]
I just need some help in order for the result to come back then the code to continue.