2013-03-14 40 views
2

我在PHP的if语句:如何在Node JS中编写非阻塞if语句?

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

第一个条件是真/假布尔检查。

第二个条件调用函数来查看数据库表中是否存在行并返回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 (isTrue and db_record_exists(id, callback)) { 
... 
} 

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

任何意见将不胜感激。

(提前)感谢您的帮助。

+0

你可能需要尝试改变你写这部分的方式。数据库查询是异步的,你试图做的是同步。 – eburgos 2013-03-14 20:14:00

回答

6

首先检查变量,然后检查回调中的异步调用结果。

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

function nope() { 
    // does not exist 
} 
-4

也许这样?

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

您需要为if和else部分使用回调。那么,“鸟巢”和条件:

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