2015-10-24 12 views
7

tickは、nodejsイベントループがキュー内のすべてを実行することを決定する実行単位ですが、明示的にprocess.nextTick()というイベント以外にnode.jsイベントループが新しいチックの処理を開始する原因とは異なります。それはI/Oで待っていますか? CPUバウンド計算はどうでしょうか?それとも、新しい機能を入力するときはいつですか?tickがnode.jsで終わるときに指定するイベントは?

答えて

0

nextTickは、現在実行中のJavascriptが制御をイベントループに戻すときに呼び出されるコールバックを登録します(たとえば、実行を終了します)。 CPUバウンド操作の場合、これは関数が終了したときに行われます。非同期操作では、非同期操作が開始され、他の即時コードが実行されたとき(非同期操作自体が完了したときで、イベント・キューからのサービスが終了したときにイベント・キューに入るようなものではない) 。 node.js doc for process.nextTick()から

現在のイベントループターンが完了するまで実行されると、コールバック関数を呼び出します。

これはsetTimeout(fn、0)の単純なエイリアスではなく、効率的には です。イベントループの後続のティックで、追加のI/Oイベント(タイマーを含む)が実行される前に実行されます( )。

いくつかの例:

console.log("A"); 
process.nextTick(function() { 
    // this will be called when this thread of execution is done 
    // before timers or I/O events that are also in the event queue 
    console.log("B"); 
}); 
setTimeout(function() { 
    // this will be called after the current thread of execution 
    // after any `.nextTick()` handlers in the queue 
    // and after the minimum time set for setTimeout() 
    console.log("C"); 
}, 0); 
fs.stat("myfile.txt", function(err, data) { 
    // this will be called after the current thread of execution 
    // after any `.nextTick()` handlers in the queue 
    // and when the file I/O operation is done 
    console.log("D"); 
}); 
console.log("E"); 

出力:

A 
E 
B 
C 
D 
3

process.nextTick()は、Node.jsのは、新しいダニを開始することはありません。これは、提供されたコードが次のティックを待つようにします。

これはそれを理解するための素晴らしいリソースです:http://howtonode.org/understanding-process-next-tick

を限りダニのためのイベントを取得することと、私はランタイムがそれを提供して信じていません。あなたが「偽」それが好きでした:

var tickEmitter = new events.EventEmitter(); 
function emit() { 
    tickEmitter.emit('tick'); 
    process.nextTick(emit); 
} 
tickEmitter.on('tick', function() { 
    console.log('Ticked'); 
}); 
emit(); 

編集を:What exactly is a Node.js event loop tick?

:あなたの他の質問のいくつかに答えるために、別のポストは、実証の例外的な仕事をしていません
関連する問題