2

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.

1
  • You might need to try to change the way you write that part. The DB query is async and what you are trying to do is sync. Commented Mar 14, 2013 at 20:14

3 Answers 3

6

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
}
Sign up to request clarification or add additional context in comments.

Comments

1

You will need to use callbacks for the if and the else part. Then "nest" the and-conditions:

if ($isTrue) {
    db_record_exists(id, function(result) {
        if (result)
            doesExist();
        else
            doesntExist();
    });
else
   doesntExist();

For convenience, you could wrap all that in a helper function (and if you need it multiple times, put in a library):

(function and(cond, async, suc, err) {
    if (cond)
        async(function(r) { (r ? suc : err)(); });
    else
        err();
})($isTrue, db_record_exists.bind(null, id), function() {
    …
}, function() {
    …
});

Comments

-4

Maybe this way?

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.