Node.js被认为是异步、事件驱动和非阻塞I/O的,但我怎么知道我的脚本是异步的?还是非阻塞的?
Node.js被认为是异步、事件驱动和非阻塞I/O的,但我怎么知道我的脚本是异步的?还是非阻塞的?
我不知道有哪些工具可以回答“输入的代码是异步还是同步”的真假问题:)
或者你可以分享代码或一些更多的上下文吗?
编辑:
你能给一个阻塞或非异步代码的例子吗? - hexacyanide
这个问题在这里有讨论:JavaScript何时是同步的?
同步代码可能像这样:
”console.log("first");
console.log("second");
console.log("third");
function f() {
alert("first");
}
function g() {
alert("second");
}
// defer execution for 1000 ms
setTimeout(f, 1000);
// defer execution for 500 ms
setTimeout(g, 500);
// run immediately
alert("third");
process.nextTick( ... )
setTimeout( ... )
setInterval( ... )
var fs = require( 'fs' );
fs.rename( ... )
fs.stat( ... )
fs.readFile( ... )
fs.writeFile( ... )
fs...
fs
操作,基本上都有它们的同步版本,在末尾添加“Sync”后缀(虽然应该避免使用同步版本)。callback
作为参数的东西都是异步的(或依赖于异步操作),例如:process.nextTick( function( ) { // <--- the callback
console.log( 'nextTick' );
});
console.log( 'test' ); // <--- will fire before the callback, i.e. asynchronouos
var arr = [ 1, 2, 3 ];
arr.forEach( function(el) { // <--- the callback
console.log( el );
});
console.log( 'test' ); // <--- will fire after the callback, i.e. synchronous
process.nextTick
的例子中,您可以更改process.nextTick
和console.log('test')
的顺序,结果仍将保持不变。