包装process.nextTick导致超出最大调用堆栈大小

我想包装process.nextTick函数,但导致recursion。

var actual = process.nextTick; process.nextTick = function(callback) { console.log('next tick called'); actual.apply(this, arguments); } console.log('starts'); setTimeout(function(){ console.log('set timeout called'); }, 100); 

这个代码产生

 starts next tick called next tick called ... RangeError: Maximum call stack size exceeded 

谁能解释工作stream程?

我非常确定console.log()正在调用process.nextTick()并导致recursion。

看看下面的例子:

 var counter = 0; var actual = process.nextTick; process.nextTick = function () { counter++; actual.apply(this, arguments); } console.log('starts ...'); // This will increment counter with 1, counter = 1 process.nextTick(function () { console.log('nextTick callback'); // This will increment counter with 1, counter = 3 console.log(counter); // This will increment counter with 1, counter = 4 }); console.log('something else ...'); // This will increment counter with 1, counter = 2 /* * OUTPUT */ starts ... something else ... nextTick callback 4 

现在,如果我们删除一个console.log()调用,我们可以看到以下内容:

 var counter = 0; var actual = process.nextTick; process.nextTick = function () { counter++; actual.apply(this, arguments); } console.log('starts ...'); // This will increment counter with 1, counter = 1 process.nextTick(function () { console.log(counter); // This will increment counter with 1, counter = 3 }); console.log('something else ...'); // This will increment counter with 1, counter = 2 /* * OUTPUT */ starts ... something else ... 3 

请注意,计数器现在是3

所以我的结论是process.nextTick()覆盖函数内的console.log()正在引起recursion。

我希望这个例子将帮助你清除这些东西:)