Search code examples
javascriptnode.jsblockingnonblocking

How to write a non-blocking if statement in Node JS?


I have an if statement in php:

if ( $isTrue && db_record_exists($id)) { ... } 
else { ... };

The first condition is a true / false boolean check.

The second condition calls a function to see if a row exists in a database table and returns true or false.

I want to rewrite this conditional in Node JS so that it is non-blocking.

I have rewritten db_record_exists as follows...

function db_record_exists(id, callback) {
  db.do( "SELECT 1", function(result) { 
    if (result) { callback(true); }
    else { callback(false); }
  );
}

...but I can't see how to then incorporate this into a larger if statement, with the boolean check. For example, the following statement doesn't make sense:

if (isTrue and db_record_exists(id, callback)) {
...
}

What is the "node" way to write this?

Any advice would be much appreciated.

Thanks (in advance) for your help.


Solution

  • Check the variable first, then check the result of the async call inside the callback.

    if (isTrue) db_record_exists(id, function(r) {
        if (r) {
            // does exist
        } else nope();
    });
    else nope();
    
    function nope() {
        // does not exist
    }