是“if(somefunction())”在node.js阻塞?

test = function(x){ if ( some conditions ) { return true; } else { return false; } } if (test(y)) {document.write("You have done this before!")​}​;​ console.log("Checked!"); 

目的是检查用户是否执行了过去的某个操作。 这些只是模拟代码,并不真正反映我实际上正在做什么。

题:

我对node.js比较新,所以请原谅我,如果这听起来微不足道。 假设testing(y)是真的。 我能确定console.log将在document.write之后执行吗? 即使testing(y)需要很长时间才能运行?

换句话说,我需要“if(test(y))…”来阻止。 我明白,传递一个函数作为参数,例如setInterval(test(y),100); 可以是asynchronous和非阻塞的。 但是如果“(testing(y))…”呢?

NodeJS具有同步(阻塞)和asynchronous(非阻塞)function。 (更准确地说,函数本身总是“阻塞”,但是其中的一个类会启动一些将在稍后完成的事情,然后立即返回,而不是等待事情完成,这就是我所说的“非阻塞”。

在大多数情况下,默认是asynchronous的(他们接受一个callback,当他们开始的事情完成); 同步的往往有名字以Sync结尾。

例如, exists是asynchronous(非阻塞),它没有返回值,而是在完成时调用callback。 existsSync是同步的(阻塞); 它返回结果而不是callback。

如果test是您自己的function,并且只调用同步function,那么它是同步的:

 function test(x) { // Obviously a nonsense example, as it just replicates `existsSync` if (existsSync(x)) { // The file exists return true; } return false; } // This works if (test("foo.txt")) { // ... } 

如果它调用一个asynchronous函数,它是asynchronous的,所以它不能通过返回值来返回结果,这个返回值可以通过if来testing:

 // WRONG, always returns `undefined` function test(x) { var retVal; exists(x, function(flag) { retVal = flag; }); return retVal; } 

相反,你必须提供一个callback:

 function test(x, callback) { exists(x, function(flag) { callback(flag); }); } // This works test("foo.txt", function(flag) { if (flag) { // ... } }); 

是的,这个代码是同步执行和“阻塞”。 但是console.log会在脚本每次运行的时候执行,因为你只在if语句中省略了document.write。

阻塞/非阻塞的术语在这里有点混乱,我会说'Node.JS中的所有函数都是阻塞的,并且节点标准库中的所有IO都是非阻塞的,除非在函数名称中同步后缀明确指示。