我正在编写一个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(){});谢谢你的帮助!
发布于 2013-09-23 21:08:51
最好避免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);
}
};https://stackoverflow.com/questions/18968443
复制相似问题