0

I have two functions fun1() and fun2() in fun1 ,fun2 is called which returns status on which basis rest of the code works in fun1 but before fun2 return fun1 rest of the code is been executed ! Because node js is a Unblocked procedural code based one ! How to handle my case ?

    async function isDuplicateUser(emailId)
{
  var condition=false;
  var con = mysql.createConnection({
    host:"localhost",
    user: "root",
    password: "32577488",
    database:"mydb"
  });
  var sql='SELECT count(*) AS namesCount FROM UserDetails WHERE emailId ="'+emailId+'";';
  con.connect(function(err) {
    con.query(sql, function (err, result) {
      if (err){
        throw err;
        return ;
      }
      if(result[0].namesCount>=1)
      {
        condition=true;
        console.log("Upper check :"+condition);
      }
    });
  });
  console.log("Lower check :"+condition);
  return condition;
}

In logger I am seeing LowerCheck at first and then Upper check logger please help me !

6
  • 3
    This is not clear at all, post the code that you're struggling with, it sounds like the issue isn't Node at all, but asynchronicity ?
    – adeneo
    Commented Jun 3, 2018 at 11:43
  • Please see now !
    – Bharadwaj
    Commented Jun 3, 2018 at 12:08
  • I see, you're using async functions, and need to learn how to work with those, see the duplicate for a good explanation on how it works
    – adeneo
    Commented Jun 3, 2018 at 12:29
  • stackoverflow.com/questions/14220321/…
    – adeneo
    Commented Jun 3, 2018 at 12:29
  • Please see the question now !
    – Bharadwaj
    Commented Jun 3, 2018 at 12:45

1 Answer 1

1

You can solve this problem with:

  1. Callbacks (only pure ES5 solution)
  2. Promises (my solution below)
  3. Async functions (also uses Promises)

Because Promises are the most intuitive for me I wrote working solution in ES6 and with Promises:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const mysql = require('mysql');

const connectionConfig = {
  host:"localhost",
  user: "root",
  password: "",
  database:"mydb"
}

/** Firstly, connect with DB; so you will be able to share connection */
const conn = mysql.createConnection(connectionConfig);
conn.connect((err) => {
  if (err) throw err;

  /** After then create server */
  app.use(bodyParser.urlencoded({ extended: true }));
  app.use(bodyParser.json());

  app.get('/',(req,res) => { res.send(`hello express`) });
  app.get('/about',(req,res) => { res.send(`Thank you!`) });

  app.post('/signup', (req, res) => {

    isDuplicateUser(req.body.email)
      .then((userPresent) => {

        if(userPresent) {
          console.log(`User Already present`);
          res.status(409).json({message: `User already present`});
        } else {
          const query = `INSERT INTO UserDetails (email, password, name) VALUES ('${req.body.email}', '${req.body.password}','${req.body.name}')`;
          conn.query(query, function (err, result) {
            if (err) throw err;
            console.log(`1 record inserted`);
            res.status(200).json({message: `1 record inserted`});
          });
        }

      })
      .catch((err) => {
        console.log(`An unexpected error occurred`);
        res.status(500).json({message: `An unexpected error occurred`});
      });

  });

  app.listen(8080, () => console.log('Server running at http://127.0.0.1:8080/') );

  function isDuplicateUser(email) {
    return new Promise((resolve, reject) => {
      const query = `SELECT count(*) AS namesCount FROM UserDetails WHERE email='${email}';`;
      conn.query(query, (err, result) => {
        if (err) reject(err);
        resolve(result[0].namesCount > 0 ? true : false);
      });
    })
  }

});

Please, notice that I renamed names of columns in DB.

I hope, this example will help you understand how to work with async code.

3
  • Thank you so much ! But May I know why app.post or app.get is in con.connect !
    – Bharadwaj
    Commented Jun 3, 2018 at 15:19
  • Technically, in this case, you can move app.get before conn.connect. However, to prepare the response app.post uses conn so it needs to be inside conn.connect. In general, it is good practice to run server after setting a connection with a database. Indeed whole this code should be separated into minimum three files: db.js (to set and handle connection), server.js (to handle routes), index.js (to connect it all together). But there is not enough space here to explain how to do it ;/ Commented Jun 3, 2018 at 15:49
  • Making it this way helps you prevent from displaying errors on front-end when the connection was not set yet. Commented Jun 3, 2018 at 15:56

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.