2013-07-09 95 views
-2

我有一个服务器上运行的node.js代码,并想知道它是否阻塞或不。这是一种类似于此:下面的node.js代码是阻塞的还是非阻塞的?

function addUserIfNoneExists(name, callback) { 
    userAccounts.findOne({name:name}, function(err, obj) { 
     if (obj) { 
      callback('user exists'); 
     } else { 

      // Add the user 'name' to DB and run the callback when done. 
      // This is non-blocking to here. 
      user = addUser(name, callback) 

      // Do something heavy, doesn't matter when this completes. 
      // Is this part blocking? 
      doSomeHeavyWork(user); 
     } 
    }); 
}; 

一旦addUser完成doSomeHeavyWork功能运行,并最终放置东西回来到数据库中。这个函数需要多长时间并不重要,但它不应该阻塞服务器上的其他事件。

那么,是否有可能测试node.js代码是否结束阻塞?

+6

你问是否doSomeHeavyWork块?我们如何在没有看到该函数的代码的情况下回答? –

回答

1

一般来说,如果它到达另一个服务,如数据库或web服务,那么它是非阻塞的,你需要有某种回调。然而,任何函数都会阻塞,直到返回什么东西(即使没有任何内容)...

如果doSomeHeavyWork函数是非阻塞的,那么很可能无论您使用哪种库都允许某种回调。所以,你可以写函数接受回调,像这样:

var doSomHeavyWork = function(user, callback) { 
    callTheNonBlockingStuff(function(error, whatever) { // Whatever that is it likely takes a callback which returns an error (in case something bad happened) and possible a "whatever" which is what you're looking to get or something. 
    if (error) { 
     console.log('There was an error!!!!'); 
     console.log(error); 
     callback(error, null); //Call callback with error 
    } 
    callback(null, whatever); //Call callback with object you're hoping to get back. 
    }); 
    return; //This line will most likely run before the callback gets called which makes it a non-blocking (asynchronous) function. Which is why you need the callback. 
}; 
+0

谢谢。这意味着我需要以非阻塞的方式编写'doSomeHeavyWork'。 – psiphi75

+0

@ psiphi75不一定,请参阅我的编辑。 – kentcdodds

1

应避免在您的Node.js代码同步块的任何部分不调用系统或I/O操作和计算需要很长时间(在计算机意义上),例如迭代大数组。而是将这种类型的代码移动到单独的工作人员,或者使用process.nextTick()将其分成更小的同步部分。你可以找到解释process.nextTick()here,但也读取所有评论。