我在服务器上运行了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代码是否最终阻塞?
答案 0 :(得分: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.
};
答案 1 :(得分:1)
你应该避免在你的Node.js代码同步块的任何部分中不调用系统或I / O操作以及哪些计算需要很长时间(在计算机意义上),例如迭代大数组。而是使用process.nextTick()将此类代码移动到单独的worker或将其划分为更小的同步片段。您可以找到process.nextTick()here的说明,但也可以阅读所有评论。