2013-11-25 17 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

你在說什麼樣的例子? –