Javascript/ Node.js not waiting for sql query to come back with a response before it continues the code












-1















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.










share|improve this question























  • How do you know that 'con' is ready for use, createConnection may not be done before progressing to con.connect, can you display 'con' to the console before using?

    – SPlatten
    Nov 21 '18 at 8:21











  • Your right, the state is disconnected before and after the con.connect call

    – Dan Jakobson
    Nov 21 '18 at 8:32











  • Can you wait for the connection and take appropriate action on failure or success?

    – SPlatten
    Nov 21 '18 at 8:38











  • Can you give some example code as I've tried await con.connect to no avail.

    – Dan Jakobson
    Nov 21 '18 at 8:39











  • Sorry, I'm not familiar with the API you are using, there must be some way of waiting or a callback to act on the result.

    – SPlatten
    Nov 21 '18 at 8:40
















-1















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.










share|improve this question























  • How do you know that 'con' is ready for use, createConnection may not be done before progressing to con.connect, can you display 'con' to the console before using?

    – SPlatten
    Nov 21 '18 at 8:21











  • Your right, the state is disconnected before and after the con.connect call

    – Dan Jakobson
    Nov 21 '18 at 8:32











  • Can you wait for the connection and take appropriate action on failure or success?

    – SPlatten
    Nov 21 '18 at 8:38











  • Can you give some example code as I've tried await con.connect to no avail.

    – Dan Jakobson
    Nov 21 '18 at 8:39











  • Sorry, I'm not familiar with the API you are using, there must be some way of waiting or a callback to act on the result.

    – SPlatten
    Nov 21 '18 at 8:40














-1












-1








-1








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.










share|improve this question














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.







javascript mysql node.js promise






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 21 '18 at 8:10









Dan JakobsonDan Jakobson

1




1













  • How do you know that 'con' is ready for use, createConnection may not be done before progressing to con.connect, can you display 'con' to the console before using?

    – SPlatten
    Nov 21 '18 at 8:21











  • Your right, the state is disconnected before and after the con.connect call

    – Dan Jakobson
    Nov 21 '18 at 8:32











  • Can you wait for the connection and take appropriate action on failure or success?

    – SPlatten
    Nov 21 '18 at 8:38











  • Can you give some example code as I've tried await con.connect to no avail.

    – Dan Jakobson
    Nov 21 '18 at 8:39











  • Sorry, I'm not familiar with the API you are using, there must be some way of waiting or a callback to act on the result.

    – SPlatten
    Nov 21 '18 at 8:40



















  • How do you know that 'con' is ready for use, createConnection may not be done before progressing to con.connect, can you display 'con' to the console before using?

    – SPlatten
    Nov 21 '18 at 8:21











  • Your right, the state is disconnected before and after the con.connect call

    – Dan Jakobson
    Nov 21 '18 at 8:32











  • Can you wait for the connection and take appropriate action on failure or success?

    – SPlatten
    Nov 21 '18 at 8:38











  • Can you give some example code as I've tried await con.connect to no avail.

    – Dan Jakobson
    Nov 21 '18 at 8:39











  • Sorry, I'm not familiar with the API you are using, there must be some way of waiting or a callback to act on the result.

    – SPlatten
    Nov 21 '18 at 8:40

















How do you know that 'con' is ready for use, createConnection may not be done before progressing to con.connect, can you display 'con' to the console before using?

– SPlatten
Nov 21 '18 at 8:21





How do you know that 'con' is ready for use, createConnection may not be done before progressing to con.connect, can you display 'con' to the console before using?

– SPlatten
Nov 21 '18 at 8:21













Your right, the state is disconnected before and after the con.connect call

– Dan Jakobson
Nov 21 '18 at 8:32





Your right, the state is disconnected before and after the con.connect call

– Dan Jakobson
Nov 21 '18 at 8:32













Can you wait for the connection and take appropriate action on failure or success?

– SPlatten
Nov 21 '18 at 8:38





Can you wait for the connection and take appropriate action on failure or success?

– SPlatten
Nov 21 '18 at 8:38













Can you give some example code as I've tried await con.connect to no avail.

– Dan Jakobson
Nov 21 '18 at 8:39





Can you give some example code as I've tried await con.connect to no avail.

– Dan Jakobson
Nov 21 '18 at 8:39













Sorry, I'm not familiar with the API you are using, there must be some way of waiting or a callback to act on the result.

– SPlatten
Nov 21 '18 at 8:40





Sorry, I'm not familiar with the API you are using, there must be some way of waiting or a callback to act on the result.

– SPlatten
Nov 21 '18 at 8:40












2 Answers
2






active

oldest

votes


















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






share|improve this answer

































    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






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53407675%2fjavascript-node-js-not-waiting-for-sql-query-to-come-back-with-a-response-befor%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      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






      share|improve this answer






























        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






        share|improve this answer




























          0












          0








          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






          share|improve this answer















          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







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 21 '18 at 9:10

























          answered Nov 21 '18 at 9:04









          Arul Vyas MohanArul Vyas Mohan

          12




          12

























              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






              share|improve this answer




























                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






                share|improve this answer


























                  0












                  0








                  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






                  share|improve this answer













                  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







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 21 '18 at 9:17









                  Anton PastukhovAnton Pastukhov

                  1978




                  1978






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53407675%2fjavascript-node-js-not-waiting-for-sql-query-to-come-back-with-a-response-befor%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      這個網誌中的熱門文章

                      Xamarin.form Move up view when keyboard appear

                      Post-Redirect-Get with Spring WebFlux and Thymeleaf

                      Anylogic : not able to use stopDelay()