0

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.

Daniel
  • 45
  • 6

2 Answers2

0

According to my view, The best possible way of solving this is by using callbacks in Node js.

Node js executes codes sychronously, let me explain by explaining what happened at your code

database_results.push(connect_to_DB.connect_to_db(sql_query));
console.log(database_results);

Here in your code console.log(database_results) is returned before executing the function connect_to_DB.connect_to_db(sql_query))

Your DBConnection.js can be modified as:

const sql = require('mysql');

exports.connect_to_db = function (sql_query, callback) {
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) callback(err);
    console.log('Data received from the DB');
    console.log(result);
    callback(result);
});

con.end((err) => { });
};

and the external js that calls the function connect_to_db function can be modified as:

'use strict';

const connect_to_DB = require('DB_Connection');
let sql_query = "SELECT * FROM table";
connect_to_DB.connect_to_db(sql_query, function (data, err) {
  if (err) {
    console.log(err);
  }
  else {
    database_results.push(data);
  }
});

console.log(database_results);

to know more about callbacks visit

0

You don't need to use promises and async/await in the same piece of code. Try something like this:

module.exports =
{
    connect_to_db: async 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!");
        });

        return await con.query(sql_query);
    }
};

and then

const connect_to_DB = require('DB_Connection');     
let sql_query = "SELECT * FROM table";
database_results.push(await connect_to_DB.connect_to_db(sql_query));
console.log(database_results);

Note that sice await keyword id only allowed inside async functions, this line database_results.push(await connect_to_DB.connect_to_db(sql_query)); should be inside an async function to work

Anton Pastukhov
  • 588
  • 2
  • 11