0

I have a function isValidCode(code) which evaluates to true and returns a boolean(I've checked the type using typeof()).

I use this function as the conditional of an if statement:

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

This is not working for some reason, and the else statement is executed even though the function evaluates to true. Why is this? I'm using node.js.

isValid function:

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;
});
Kinnard Hockenhull
  • 2,790
  • 5
  • 27
  • 34

2 Answers2

0

The function you pass to the client.query is a callback. That will be called asynchronously once the query returns. BUT isValidCode won't wait for that callback before returning. It will call client.query and proceed to the next line, which is the return statement. The function will return before the value of valid could be set to anything.

Scott
  • 439
  • 3
  • 9
0

isValidCode is an asynchronous function. That means at the time of evaluation in the if statement, isValidCode will evaluate as undefined hence the code in the "else" section runs.

You can rewrite this function as a callback or event. Here is the callback version

isValidCode(code, function(result){
    if(result){
        // do stuff if result is true
    } else {
        // otherwise, do other stuff
    }
});
takinola
  • 1,643
  • 1
  • 12
  • 23