节点JS同步数据库调用
我很新的Java脚本和nodejs。 我想写一个代码,检查数据库中是否已经存在一个电子邮件,如果不发送错误。 问题是在数据库函数结束之前,我的代码进入下一行,导致未定义的variables(emailExists)
这是我注册的代码:
app.post('/signUpWeb', function (req, res) { var reqBody = req.body; var email= reqBody.email; var password= reqBody.password; var fullName= reqBody.fullName; var webDbInsertion = {email: email, password: password, fullName: fullName}; var emailExists= DButils.checkIfPKexists(connection, "webusersMail", "email", webDbInsertion.email); if(emailExists == false){ DButils.insertInfoToDB(connection, "webusersMail" ,webDbInsertion); console.log("successfull signup"); res.send("successfull signup"); }else{ console.log("signup failed, email: " + email + " allready exits"); res.send("signup failed"); } res.end(); });
这是我的数据库调用
exports.checkIfPKexists= function(dbConnection, tableName, PK, newPK){ var query = dbConnection.query('select count(*) as mailPkCount from ' +tableName+ ' where ' +PK+ ' = ?', newPK, function (err, row, result) { if (err) { console.error(err); return; } var count= row[0].mailPkCount; var bool = (count > 0); return bool; }); };
那么你看,node.JS被devise成asynchronous的,而你所要求的并不是不可能的,它会closures为你的服务器运行事件循环的主线程。
我build议做的是在你的“checkIfPKexists”函数中join一个callback函数,并返回结果作为参数,就像你在DBConnection.query中一样。 然后你将所有未被初始化的代码移动到你的callback中。
编辑:下面是一个快速的代码示例,根据您的喜好进行打磨http://pastebin.com/bEHp4bi2
- 用Express框架提供图像
- 在express node.js中在控制台上打印mongoose结果的值
- 使用streamlinejs和nodejsexpression框架
- Express.js使用路由器与App.use路由的好处?
- 如何从Express中的http请求中获取未parsing的查询string
- 为什么express.js在使用res.send()的时候返回一个空的数组?
- Phantomjs page-break-after:总是创造空间
- Node.js + Express + simpledb; “TypeError:尝试列出域时,无法读取属性”错误的null“
- 如何用Express后台构build多个布局的Angular JS