我正在尝试包装process.nextTick函数,但这会导致递归。
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
任何人都可以解释工作流程吗?
答案 0 :(得分:0)
我非常确定console.log()
正在调用process.nextTick()并导致递归。
查看以下示例:
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 。
所以我的结论是console.log()
内部process.nextTick()
覆盖函数导致了递归。
我希望这个例子可以帮助你清除这些事情:)