Javascript函数在应该返回真值的地方返回了假

Javascript function is returning false where it should be returning true

本文关键字:返回 方返回 函数 Javascript      更新时间:2023-09-26

我写了一个node.js模块。我的模块有一个isValid方法,它使用给定令牌作为查找值从数据库读取数据。如果数据有效,则调用setData方法,如果数据有效则返回true,否则返回false。

根据我记录到控制台的一些消息,函数应该返回true,但是当我做' if…else…' '检查,它总是返回false。

这是我的模块

var db = require('./dbconnect');
var PHPUnserialize = require('php-unserialize');

function validator (){
  this.icws = null;
};

/**
* @setData
*
* Set the value of the icwsData
*
* @return void
*/
validator.prototype.setData = function (icws){
  this.icws = icws;
};

/**
* @getData
*
* Get the value of the icwsData
*
* @return object
*/
validator.prototype.getData = function (){
  return this.icws;
};

/**
* @isValid
*
* Checks if a token is valid or not
*
* @params (string) tokenId: the PHP sessionId
* @params (string) myIP: the user IP address
* @params (integer) duration: the duration to keep the session good for in microseconds
*
* @return bool
*/
validator.prototype.isValid = function (tokenId, myIP, duration){
  if(!tokenId || !myIP){
    console.log('Missing TokenID or IP Address');
    return false;
  }
  if(!duration){
    duration = 3600;
  }
  var self = this;
  db.sqlConnection('SELECT ' +
                   '  su.icws_username AS username ' +
                   ', su.icws_password AS password ' +
                   ', su.icws_workstation AS workstation ' +
                   ', icws.host ' +
                   ', icws.port ' +
                   ', s.data ' +
                   'FROM sessions AS s ' +
                   'INNER JOIN view_users AS su ON su.user_id = s.user_id ' +
                   'INNER JOIN icws_servers AS icws ON icws.server_id = su.icws_server_id ' +
                   'WHERE s.session_id = ? '
                   , [tokenId] , function(err, rows){

    if(err){ 
      console.log(err);
      return false;
    }
    if(!rows[0] || !rows[0].data){
      console.log('No match found for this token!');
      return true;
    }
    var data = PHPUnserialize.unserializeSession(rows[0].data);
    var now = Math.floor(new Date() / 1000);
    if(!data.MA_IDLE_TIMEOUT || (data.MA_IDLE_TIMEOUT + duration) < now){
      console.log('The session Times out!');
      return false;
    }
    if(!data.MA_IP_ADDRESS || myIP != data.MA_IP_ADDRESS){
      console.log('This session have been hijacked!');
      return false;
    }
    self.setData(rows[0]);
    console.log('Good - return true!');
    return true;
  });
};

module.exports = validator;
下面是我如何调用模块
var sessionValidator = require('./modules/validator.js');
var sessionChecker = new sessionValidator();
var boo = sessionChecker.isValid(decodedToken, myIP, env.session.duration);
if(boo){
    console.log('Worked!');
} else {
    console.log('No Go!');
}
return;
控制台打印
Good - return true!
No Go!

我期待我的输出

Good - return true!
Worked!

为什么这个函数总是返回false?

如果你需要看到我的dbconnect模块,这里是它的代码

// Dependencies
var mysql   = require('mysql'),
    env  = require('./config');
/**
 * @sqlConnection
* Creates the connection, makes the query and close it to avoid concurrency conflicts.
*
* @param (string) sql: the sql query
* @param (array) values: contains values to sanitize for the query
* @param (function) next: call back function that will have data set if a select query is passed
*
* @return void
*/  
exports.sqlConnection = function (sql, values, next) {
    // It means that the values hasnt been passed
    if (arguments.length === 2) {
        next = values;
        values = null;
    }
    var connection = mysql.createConnection({
          host: env.mysql.host,
          user: env.mysql.user,
          password: env.mysql.password,
          database: env.mysql.database
    });
    connection.connect(function(err) {
        if (err !== null) {
            console.log("[MYSQL] Error connecting to mysql:" + err );
        }
    });
    connection.query(sql, values, function(err) {
        connection.end(); // close the connection
        if (err) {
            throw err;
        }
        // Execute the callback
        next.apply(this, arguments);
    });
}

编辑

当前输出实际上是

No Go!
Good - return true!

数据库访问本身是异步的。

实际发生的是isValid返回undefined (false,但不显式地返回false),因此条件表示无效。

通常使用===并检查类型以及true/false是有意义的:它可能有助于指出代码没有按照您的期望工作的原因/位置。

如注释所示,使用回调或承诺是规范的方法。