【问题标题】:Infinite loop in module not working模块中的无限循环不起作用
【发布时间】:2015-03-29 23:08:24
【问题描述】:

我正在尝试编写一个 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)

【问题讨论】:

    标签: node.js node-modules


    【解决方案1】:
       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);
        });
    }
    

    【讨论】:

    • 您还需要保存上下文。查看更新的答案。
    猜你喜欢
    • 2013-05-30
    • 1970-01-01
    • 1970-01-01
    • 2013-06-25
    • 2016-04-19
    • 2011-12-19
    • 2014-12-17
    • 2021-03-31
    相关资源
    最近更新 更多