将函数求值为节点中的条件函数

Evaluate function as conditional in Node

本文关键字:函数 条件 节点      更新时间:2023-09-26

我有一个函数isValidCode(code),它的计算结果为true并返回布尔值(我使用typeof()检查了类型)。

我使用这个函数作为if语句的条件:

if(isValidCode(code)){
    console.log('Code is valid!');
}else{
    console.log('Code is not valid!');
}

由于某些原因,这不起作用,即使函数的计算结果为true,else语句也会执行。为什么会这样?我使用的是node.js.

isValid函数:

exports.isValidCode = pool.pooled(function(client, Code){
  var valid;
  client.query('SELECT EXISTS(SELECT * FROM codes where code = $1)', [Code], function(err,result){
    if (err) console.log('isValidCode error: ' + err);
    console.log('isValidCode?: ' + result.rows[0].exists);
    valid=result.rows[0].exists;
    console.log(typeof(result.rows[0].exists));  
  });
  return valid;
});

传递给client.query的函数是一个回调。一旦查询返回,它将被异步调用。但是isValidCode不会在返回之前等待回调。它将调用client.query并继续执行下一行,即返回语句。函数将在valid的值设置为任何值之前返回。

isValidCode是一个异步函数。这意味着在if语句中进行求值时,isValidCode将被求值为未定义,因此"else"部分中的代码将运行。

您可以将此函数重写为回调或事件。这是回调版本

isValidCode(code, function(result){
    if(result){
        // do stuff if result is true
    } else {
        // otherwise, do other stuff
    }
});