[英]node.js non blocking code example failure
通過此鏈接http://greenash.net.au/thoughts/2012/11/nodejs-itself-is-blocking-only-its-io-is-non-blocking/我正在嘗試編寫兩個非阻塞函數的代碼:
阻止代碼:
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(“短氣泡末端”);“ 應該首先顯示?
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');
});
但這是行不通的。 我究竟做錯了什么?
添加回調不會使您的代碼異步。 由於Javascript是一種單線程語言,因此在給定時間僅執行一條指令。 這意味着無論您做什么,此代碼片段都將永遠掛起:
function a() {
while (true) {}
}
a();
console.log('Done.');
要稍后 (即異步)處理一些代碼,可以使用process.nexTick()
或setImmediate
:
function LongBucle(callback) {
setImmediate(function() {
for (x=0;x<=10000;x++) {
console.log(x);
}
callback(x);
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.