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 call
Solution 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
}
Solution 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() {
…
});
Solution 3:
Maybe this way?
functiondb_record_exists(id, callback) {
db.do( "SELECT 1", function(result) { callback(result ? true : false); });
}
Post a Comment for "How To Write A Non-blocking If Statement In Node Js?"