Reputation: 179
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.
Upvotes: 1
Views: 74
Reputation: 1095
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();
Upvotes: 2