javascript - Node JS 同步数据库调用

标签 javascript node.js express

我是 java 脚本和 nodejs 的新手。 我正在尝试编写一个代码来检查数据库中是否已经存在电子邮件,如果不存在则发送错误。 问题是在数据库函数结束之前,我的代码转到下一行,导致 undefined variable (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 被设计成异步的,虽然你的要求并非不可能,但它会关闭为你的服务器实例运行事件循环的主线程。

我建议做的是向您的“checkIfPKexists”函数添加一个回调函数,并将结果作为参数返回,就像您在 DBConnection.query 中所做的那样。然后,您可以将所有未初始化的代码移动到您的回调中。

编辑:这是一个快速代码示例,根据您的喜好对其进行修饰 http://pastebin.com/bEHp4bi2

关于javascript - Node JS 同步数据库调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33725213/

相关文章:

javascript - document.getElementById().innerHTML 在 IE 中失败并显示 'Unknown Error'

javascript - 从条形码扫描时向文本区域值添加逗号

javascript - jQuery ajax() 与 get()/post()

json - 判断node.js中JSON格式对象的相等性

node.js - NPM错误: 503 Service Unavailable for npm install command

javascript - 表示没有用绝对路径加载图片

node.js - 无法从浏览器连接到 Node.js Express 服务器

javascript - 如何从标题中的链接访问 'rel'?超媒体链接关系

node.js - 类型错误 : Cannot read property 'map' of undefined in reactjs

node.js - NodeJs + Postgres 同步连接到数据库以填充变量