模块中的无限循环不起作用
Infinite loop in module not working
我正在尝试每秒编写一个 Node
模块 运行 一些代码:
function worker() {
}
worker.prototype.process = function(callback) {
console.log("doing the job");
callback();
}
worker.prototype.query_process = function(callback) {
console.log("query_process called");
this.process(function() {
console.log("Process callback called");
setTimeout(function() { this.query_process }, 1000);
});
}
worker.prototype.start = function() {
this.query_process();
}
module.exports = worker;
我是这样使用的:
var worker = require('./lib/worker');
var worker = new worker();
worker.start();
这是 运行 脚本时的输出:
& node workerTest.js
query_process called
doing the job
Process callback called
为什么这不是运行无限循环
EDIT1
在方法调用后添加括号
setTimeout(function() { this.query_process() }, 1000);
但现在出现此错误:
/Users/dhrm/Development/project/lib/worker.js:14
setTimeout(function() { this.query_process() }, 1000);
^
TypeError: undefined is not a function
at null._onTimeout (/Users/dhrm/Development/project/lib/worker.js:14:32)
at Timer.listOnTimeout (timers.js:110:15)
setTimeout(function() { this.query_process }, 1000);
您不要再给 this.query_process
打电话了。后面加括号调用函数。
回复编辑:
您还需要保存上下文以便在回调中使用:
worker.prototype.query_process = function(callback) {
var me = this;
console.log("query_process called");
this.process(function() {
console.log("Process callback called");
setTimeout(function() { me.query_process() }, 1000);
});
}
我正在尝试每秒编写一个 Node
模块 运行 一些代码:
function worker() {
}
worker.prototype.process = function(callback) {
console.log("doing the job");
callback();
}
worker.prototype.query_process = function(callback) {
console.log("query_process called");
this.process(function() {
console.log("Process callback called");
setTimeout(function() { this.query_process }, 1000);
});
}
worker.prototype.start = function() {
this.query_process();
}
module.exports = worker;
我是这样使用的:
var worker = require('./lib/worker');
var worker = new worker();
worker.start();
这是 运行 脚本时的输出:
& node workerTest.js
query_process called
doing the job
Process callback called
为什么这不是运行无限循环
EDIT1
在方法调用后添加括号
setTimeout(function() { this.query_process() }, 1000);
但现在出现此错误:
/Users/dhrm/Development/project/lib/worker.js:14
setTimeout(function() { this.query_process() }, 1000);
^
TypeError: undefined is not a function
at null._onTimeout (/Users/dhrm/Development/project/lib/worker.js:14:32)
at Timer.listOnTimeout (timers.js:110:15)
setTimeout(function() { this.query_process }, 1000);
您不要再给 this.query_process
打电话了。后面加括号调用函数。
回复编辑:
您还需要保存上下文以便在回调中使用:
worker.prototype.query_process = function(callback) {
var me = this;
console.log("query_process called");
this.process(function() {
console.log("Process callback called");
setTimeout(function() { me.query_process() }, 1000);
});
}