简体   繁体   English

如何首先调用函数

[英]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 ! 我在fun1中有两个函数fun1()和fun2(),调用fun2返回状态,在此状态下,其余代码在fun1中起作用,但在fun2返回fun1之前,其余代码已执行! Because node js is a Unblocked procedural code based one ! 因为node js是一个基于Unblocked的程序代码! 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 ! 在记录器中,我首先看到LowerCheck,然后看到Upper Check logger,请帮助我!

You can solve this problem with: 您可以使用以下方法解决此问题:

  1. Callbacks (only pure ES5 solution) 回调(仅纯ES5解决方案)
  2. Promises (my solution below) 承诺(我的解决方案如下)
  3. Async functions (also uses Promises) 异步功能(也使用Promises)

Because Promises are the most intuitive for me I wrote working solution in ES6 and with Promises: 因为Promises对我来说最直观,所以我在ES6和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. 希望本示例可以帮助您了解如何使用异步代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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