如何在Node JS中编写非阻塞if语句? [英] How to write a non-blocking if statement in Node JS?

查看:156
本文介绍了如何在Node JS中编写非阻塞if语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在php中有一个if语句:

I have an if statement in php:

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

第一个条件是对/错布尔检查.

The first condition is a true / false boolean check.

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

The second condition calls a function to see if a row exists in a database table and returns true or false.

我想在Node JS中重写此条件,以便它是非阻塞的.

I want to rewrite this conditional in Node JS so that it is non-blocking.

我已将db_record_exists重写如下...

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); }
  );
}

...但是我看不到如何通过布尔检查将其合并到更大的if语句中.例如,以下语句没有意义:

...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?

任何建议将不胜感激.

(预先)感谢您的帮助.

Thanks (in advance) for your help.

推荐答案

请先检查变量,然后在回调内部检查异步调用的结果.

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
}

这篇关于如何在Node JS中编写非阻塞if语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆