1

I want the db query to be completed before the command line moves to next lines to execute.

Here is excerpt of my code:

const express = require('express');
const bodyparser = require('body-parser');
const mysql = require('mysql');
const app = express();
app.use(bodyparser())
var pool = mysql.createPool(
    {
        connectionLimit:40,
        host: <>
        user:<>,
        password: <>,
        database:<>
    }
)

console.log("First Print Command")

let sql = "select * FROM pinfo" 
   pool.getConnection((err,conn1)=>
   {
        if(true)
       {
           conn1.query(sql,(err1,results)=>
           {
               conn1.release()

              console.log("Second print command")

           });
       }
   })

   console.log("Third print command")

const port  = 3001;
app.listen(port, () => {
    console.log('Server is running at port '+port);
  });


This is the output I am getting

First Print Command
Third print command
Server is running at port 3001
Second print command

I want the print command to proceed in order and i have looked into async and promises but couldn't figure out the syntax as it always skipped the command, it would be helpful if you could provide an excerpt of the syntax.

4
  • You need to move Third print command within the callback if you want to achieve what you want Commented Mar 14, 2020 at 8:17
  • yes that is a solution but i have to make nested db connection , i need the data from one query to be accessed in another query and by using callback it would be problematic and i need to print the results outside the db connection. Could you help me with that ? if we can arrange the print order and make the connection terminal to execute the db connection then we can achieve the above issue. Commented Mar 14, 2020 at 8:40
  • See this answer from earlier today: stackoverflow.com/questions/60678479/…. Commented Mar 14, 2020 at 8:43
  • 1
    @sks123245 that is called 'Callback hell' , as Hemanath answer, use Promises and async/await pattern. Commented Mar 14, 2020 at 9:10

1 Answer 1

2

you can wait for the query to complete and print the third statement like this,

const express = require('express');
const bodyparser = require('body-parser');
const mysql = require('mysql');
const app = express();
app.use(bodyparser())
var pool = mysql.createPool(
    {
        connectionLimit: 40,
        host,
        user,
        password,
        database,
    }
);

console.log("First Print Command");

async function queryDB() {
    let sql = "select * FROM pinfo";
    return new Promise(function (resolve, reject) {
        pool.getConnection((err, conn1) => {
            if (true) {
                conn1.query(sql, (err1, results) => {
                    conn1.release()
                    console.log("Second print command")
                    resolve(results)
                });
            }
        })
    });
}

async function main() {
    let results = await queryDB();
    console.log("Third print command");
    const port = 3001;
    app.listen(port, () => {
        console.log('Server is running at port ' + port);
    });
}

main();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.