如何在Node JS中编写一个非阻塞的if语句?

我有一个if语句在PHP中:

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

第一个条件是true / false布尔检查。

第二个条件调用函数来查看数据库表中是否存在行,并返回true或false。

我想在Node JS中重写这个条件,所以它是非阻塞的。

我已经重写db_record_exists如下…

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

…但是我看不到如何用布尔检查把它们合并到一个更大的if语句中。 例如,下面的说法没有意义:

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

什么是“节点”的方式来写这个?

任何意见将不胜感激。

在此先感谢您的帮助。

首先检查variables,然后检查callback中asynchronous调用的结果。

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

您将需要使用callback的if和其他部分。 然后“嵌套”和条件:

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

为了方便起见,你可以把所有的东西都包装在一个辅助函数中(如果你需要多次,把它放在一个库中):

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

也许这样?

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