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

2019-07-18 14:26发布

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.

3条回答
Emotional °昔
2楼-- · 2019-07-18 14:47

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() {
    …
});
查看更多
Anthone
3楼-- · 2019-07-18 14:51

Maybe this way?

function db_record_exists(id, callback) {
  db.do( "SELECT 1", function(result) { callback(result ? true : false); });
}
查看更多
看我几分像从前
4楼-- · 2019-07-18 15:00

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
}
查看更多
登录 后发表回答