【问题标题】:How to Write an Asynchronous While Loop in Node.JS如何在 Node.JS 中编写异步 While 循环
【发布时间】:2013-09-23 20:41:27
【问题描述】:

我正在编写一个 node.js 应用程序来帮助自动化我的一些家庭啤酒厂。我正在使用的模块之一是 PID 算法来控制输出,以便它们保持某些设定点。我目前正在通过 while 循环执行此操作,但我认为此代码将被阻塞。任何使这更有效和异步的帮助将不胜感激。这是我的控制循环:

device.prototype.pid_on = function(){
    while(this.isOn){
        this.pid.set_target(this.target); // make sure that the setpoint is current
        var output_power = this.pid.update(this.current_value); // gets the new output from the PID
        this.output.set_power(output_power);
    };
};

为了便于阅读,我对其进行了一些更改,但基本上就是这样。它只会循环,调整输出,然后反馈新的输入值。我希望循环继续运行,直到设备关闭。

显然,我需要它是非阻塞的,以便在 pid 运行时我可以继续控制其他设备。

目前,我只是调用 device.pid_on();在我的代码中。

我的一个想法是使用一个空回调,这样会不会阻塞?

device.prototype.pid_on(calback){
    while (this.isOn){...};
    callback();
};

//call later in code
device.pid_on(function(){});

感谢您的任何/所有帮助!

【问题讨论】:

    标签: node.js asynchronous while-loop nonblocking pid


    【解决方案1】:

    最好避免while循环。

    device.prototype.pid_on = function() {
      var that = this;
      if ( this.isOn ) {
    
        ... do stuff
    
        process.nextTick(function() {
          that.pid_on();
        });
      }
    };
    

    或者

    device.prototype.pid_on = function() {
      var that = this;
      if ( this.isOn ) {
    
        ... do stuff
    
        setTimeout(function() {
          that.pid_on();
        }, 0);
      }
    };
    

    【讨论】:

    • 是的,我也想过这个问题。我只是重构了代码,以便如果设备打开,则只要收到新的输入值就会调用 pid_on。这消除了循环,并且应该有助于 CPU 负载,因为 pid 代码仅在输入更改时运行。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-14
    • 2015-06-26
    • 2012-07-15
    • 1970-01-01
    • 1970-01-01
    • 2020-03-27
    相关资源
    最近更新 更多