简体   繁体   English

Node.js中的回调和串行端口排水

[英]Callbacks and Serial Port Draining in Node.js

I have a function that, when you press a key, sends a keycode over a serial port. 我有一个功能,当您按下一个键时,会通过串行端口发送一个键码。 However, in this circumstance, onKey 's callback is getting activated faster than the data can be written to the serial port, so I need to use a drain function which sends all data and calls back when it's done. 但是,在这种情况下, onKey的回调被激活的速度快于将数据写入串行端口的速度,因此我需要使用流失函数来发送所有数据并在完成后进行回调。

How do I wait for the drainSerialPort callback to execute before attempting to send the next key code? 在尝试发送下一个键码之前,我如何等待执行drainSerialPort I assume there's a better way to structure the three functions. 我认为有更好的方法来构造这三个功能。

onKey(function(key) {
  writeSerial(key, function() {
    drainSerialPort(function() {
      // Wait for this callback to be called to continue
    });
  });
});

According to your requirement the best option for you is asynchronus. 根据您的要求,最适合您的选择是异步。 First your function onKey is executed, after when it completed function writeSerial is executed. 首先,您的函数onKey被执行,完成后,函数writeSerial被执行。

        var onKey = function (key) {
        };
async.eachSeries(onKey, writeSerial, function (err) {
    if (err) {
        res.json({status: 0, msg: "OOPS! How is this possible?"});
    }
    drainSerialPort(function () {
        // Wait for this callback to be called to continue
    });
    res.json("Series Processing Done");
})
var writeSerial = function (key) {
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM