我在fun1中有两个函数fun1()和fun2(),调用fun2,返回状态,其中其余代码在fun1中工作但在fun2之前返回fun1其余代码已执行!因为节点js是一个基于Unblocked程序代码的程序!如何处理我的案子?
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;
}
在记录器中,我首先看到LowerCheck,然后上检查记录器请帮助我!
答案 0 :(得分:1)
您可以使用以下方法解决此问题:
因为Promise对我来说是最直观的,所以我在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);
});
})
}
});

请注意,我在DB中重命名了列的名称。
我希望,这个例子可以帮助您了解如何使用异步代码。