How to write a non-blocking if statement in Node J

2019-07-18 15:01发布

问题:

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:

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
}


回答2:

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() {
    …
});


回答3:

Maybe this way?

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