我很困惑为什么有些人会“要求”
返回一个错误:
TypeError: require不是Timeout._onTimeout的一个函数(...........index.js:8:18)
执行下列操作时:
(()=> {
console.time("pipeline")
pipeline().then((result) => {
console.log("Then: " + result)
console.log("Work Complete for iteration: " + i + " calling iteration no:", i = i + 1)
setTimeout(arguments.callee, 1000);
}).catch((error) => {
console.error("error occured with promise resolution: " + error)
});
console.timeEnd("pipeline")
})()
它只运行一次,然后出错(即使我显然连接到数据库)。
但是,如果更改为此格式,则可以正常工作:
(function () {
console.time("pipeline")
pipeline().then((result) => {
console.log("Then: " + result)
console.log("Work Complete for iteration: " + i + " calling iteration no:", i = i + 1)
setTimeout(arguments.callee, 1000);
}).catch((error) => {
console.error("error occured with promise resolution: " + error)
});
console.timeEnd("pipeline")
})()
这个错误表明这与我认为的超时有关,因为它在抛出错误之前只执行一次。
为什么会发生这种行为?这与arguments.callee有关吗?如果是的话,原因何在?
提前谢谢你,
发布于 2018-09-12 06:22:03
arguments
是指箭头函数的父函数作用域。arguments
。
Node.js模块与模块包装函数包装在外壳下:
(function(exports, require, module, __filename, __dirname) {
// Module code actually lives in here
});
这就是arguments.callee
所指的内部箭头函数。调用arguments.callee
将导致再次使用错误的参数计算当前模块,特别是require
。
依赖arguments.callee
是很麻烦的。更好的方法是显式引用函数:
(function foo() {
...
setTimeout(foo, 1000);
...
})()
当箭头要求块作用域不将foo
泄漏到父作用域时:
{
let foo;
(foo = () => {
...
setTimeout(foo, 1000);
...
})()
}
https://stackoverflow.com/questions/52297248
复制