节点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