下面是存在於「practise01.js」文件中的代碼,爲什麼以及何時使用process.nextTick?
function fn(name){
return f;
function f(){
var n = name;
console.log("Next TICK "+n+", ");
}
}
function myTimeout(time,msg){
setTimeout(function(){
console.log("TIMEOUT "+msg);
},time);
}
process.nextTick(fn("ONE"));
myTimeout(500,"AFTER-ONE");
process.nextTick(fn("TWO"));
myTimeout(500,"AFTER-TWO");
process.nextTick(fn("THREE"));
myTimeout(500,"AFTER-THREE");
process.nextTick(fn("FOUR"));
從上面的代碼運行的輸出是
[email protected]:~/myPractise/PlainNodeJSPractise01/Process$ node practise01.js
Next TICK ONE,
Next TICK TWO,
Next TICK THREE,
Next TICK FOUR,
TIMEOUT AFTER-ONE
TIMEOUT AFTER-TWO
TIMEOUT AFTER-THREE
現在我寫的代碼,而無需使用process.nextTick,在「practise02的.js」,如下所示,
function myTimeout(time,msg){
setTimeout(function(){
console.log("TIMEOUT "+msg);
},time);
}
function fn(name){
return f;
function f(){
var n = name;
console.log("Next TICK "+n+", ");
}
}
fn("ONE")();
myTimeout(500,"AFTER-ONE");
fn("TWO")();
myTimeout(500,"AFTER-TWO");
fn("THREE")();
myTimeout(500,"AFTER-THREE");
fn("FOUR")();
運行上述代碼後輸出是
[email protected]:~/myPractise/PlainNodeJSPractise01/Process$ node practise02.js
Next TICK ONE,
Next TICK TWO,
Next TICK THREE,
Next TICK FOUR,
TIMEOUT AFTER-ONE
TIMEOUT AFTER-TWO
TIMEOUT AFTER-THREE
如果您看到兩個輸出都是相同的。
那麼在這種情況下,我需要去process.nextTick?
當我試圖閱讀更多,我明白瞭如果我需要立即執行一些函數,當事件回滾是空的比去「process.nextTick」。
那麼它與我的第二種方法有什麼不同?
請給我解釋一下或者給我一些指點在您的文章
因爲您使用*僅*'console.log'或*僅*'process.nextTick'你看不到的差異。做控制檯日誌,然後打勾,console.log,你會看到不同之處。 – Azamantes
我沒有明白。你能否詳細說明 –