Node.js承诺并回调和异步

时间:2018-07-12 01:06:06

标签: node.js

因此,我已经完成了C ++ Java和PHP的工作,并希望对Node.js有所帮助。下面有一个非常简单且不安全的SQL查询。

module.exports = {
  LoginCheck: function(data,cb){
    console.log(data.password);
    console.log(data.username);
    if(data.username && data.password){
        console.log('we have arrived');
        var config = require(__dirname+'/../Config/config.json');
        var mysql = require('mysql');
        var con = mysql.createConnection({
            host: config.LoginDBhost,
            port: config.LoginDBport,
            user: config.LoginDBusername,
            password: config.LoginDBpassword,
            database: config.LoginDB
            });
        con.connect(function(err) {
          if (err) throw err;
            console.log('we have connected');
          con.query("SELECT * FROM `Users` WHERE `Username` = '"+data.username+"'", function (err, result) {
            if (err) console.log(err); 
            if(result.Password){    
                if(result[0].Password){         
                    if(result[0].Password == data.password){
                        console.log('true');
                        cb(true);
                    }       
                }
            }

          });
        });
    }   
    //either password is null or didnt match on file... if we are this far its a fail
    console.log('false');
    cb(false);
  },
  bar: function () {
    // whateverss
  }
};

该代码不等待sql连接,并跳转为false。数天来,我一直在脑海中摸索,试图弄清楚在使我的代码遵循步骤多年之后,promise和回调如何工作。

有人可以转换一下并解释在需要时如何强制我的代码同步吗?

1 个答案:

答案 0 :(得分:1)

尝试此代码:

module.exports = {
  LoginCheck: function(data,cb){
    console.log(data.password);
    console.log(data.username);
    if(data.username && data.password){
        console.log('we have arrived');
        var config = require(__dirname+'/../Config/config.json');
        var mysql = require('mysql');
        var con = mysql.createConnection({
            host: config.LoginDBhost,
            port: config.LoginDBport,
            user: config.LoginDBusername,
            password: config.LoginDBpassword,
            database: config.LoginDB
            });
        con.connect(function(err) {
          // I think cb(false) here but you use throw err.
          if (err) throw err;
          console.log('we have connected');
          con.query("SELECT * FROM `Users` WHERE `Username` = '"+data.username+"'", function (err, result) {
            if (err) console.log(err);
            if(result.Password){
                if(result[0].Password){            
                    if(result[0].Password == data.password){
                        console.log('true');
                        cb(true);
                    }
                }
            }

            //either password is null or didn't match on file... if we are this far its a fail
            console.log('false');
            cb(false);

          });
        });
    }
  },
  bar: function () {
    // whateverss
  }
};