2013-11-25 28 views
0

下面这个链接http://greenash.net.au/thoughts/2012/11/nodejs-itself-is-blocking-only-its-io-is-non-blocking/我想两个代码无阻塞功能:的Node.js非阻塞代码示例失败

阻止代码:

function LongBucle() { 
    for (x=0;x<=10000;x++) { 
     console.log(x); 
    } 
} 

function ShortBucle() { 
    for (x=0;x<=10;x++) { 
     console.log("short "+x); 
    } 
} 

LongBucle(); 
console.log("Long bucle end"); 

ShortBucle(); 
console.log("Short bucle end"); 

现在我试图把代码变成非因此阻止代码 “console.log(”Short bucle end“);”应该先显示?

function ShortBucle(callback) { 
    for (x=0;x<=10;x++) { 
     console.log("corto "+x); 
    } 
callback(x); 
} 


function LongBucle(callback) { 
    for (x=0;x<=10000;x++) { 
     console.log(x); 
    } 
    callback(x); 
} 


LongBucle(function(err) { 
    console.log('Long bucle end'); 
}); 


ShortBucle(function(err) { 
    console.log('short bucle end'); 
}); 

但它不起作用。我究竟做错了什么?

+0

调用回调仍然阻塞,请使用'setImmediate' – Fluffy

回答

1

添加回调不会使您的代码异步。由于Javascript是单线程语言,因此在给定的时间只执行一条指令。这意味着,这个片段将永远挂了,不管你做什么:

function a() { 
    while (true) {} 
} 

a(); 
console.log('Done.'); 

要处理的一些代码量(异步IE),你可以使用process.nexTick()setImmediate

function LongBucle(callback) { 
    setImmediate(function() { 
     for (x=0;x<=10000;x++) { 
      console.log(x); 
     } 
     callback(x); 
    }) 
} 

Here is an article解释process.nextTick()和JavaScript中的事件循环。

+0

谢谢setImmediate工作但我应该接受这个网页的例子是错误的? http://greenash.net.au/thoughts/2012/11/nodejs-itself-is-blocking-only-its-io-is-non-blocking/ – user3032175

+0

你在说什么样的例子? –