简体   繁体   中英

How to call a make a function call first to happen

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 !

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM