[英]How do i use function if i need to define it later?
So, I'm using node.js, express and serialport.所以,我使用的是 node.js、快递和串口。 What I need to do is to let user pick serial port which listens to, initialize it by using AJAX request and, hopefully, get some data from serial port.
我需要做的是让用户选择监听的串口,使用 AJAX 请求对其进行初始化,并希望从串口获取一些数据。 But I can't actually initizalize SerialPort object somewhere in the middle of the code, because it starts raining with "is not defined" errors.
但我实际上无法在代码中间的某个地方初始化 SerialPort object,因为它开始下雨并出现“未定义”错误。 So, my code should look like this:
所以,我的代码应该是这样的:
//some definitions here...
app.post('/submitPort', (req, res) => {
tty = new SerialPort(req.body.portpath)
})
tty.on('data', () => {...})
And so on.等等。 Even when I'm trying to declare tty earlier in the code, before submitPort , it throws bunch of errors about that it's not defined.
即使我试图在代码中更早地声明tty ,在submitPort之前,它也会引发一堆关于它未定义的错误。 And I understand this logic - I haven't initialized that object before, so, how could I do it?
而且我理解这个逻辑 - 我之前没有初始化过 object,那么,我该怎么做呢? But that also didn't work, I mean, I tried to do it like so:
但这也没有用,我的意思是,我试着这样做:
let tty = new SerialPort()
//some logic
app.post('/submitPort', (req, res) => {
tty = new SerialPort(req.body.portpath)
})
So, I'm lost now.所以,我现在迷路了。 I really need to bind web and serial together, hovewer, it glues pretty hard.
我真的需要将 web 和串行绑定在一起,但是,它非常难以粘合。 What am I supposed to do in order to make it work?
我应该怎么做才能让它发挥作用?
You need lazy init
and singleton
, then this solution can be used.您需要
lazy init
和singleton
,然后可以使用此解决方案。
const tty;
//some definitions here...
app.post('/submitPort', (req, res) => {
if(!tty){
initTTY(req.body.portpath)
} // not define init
res.send("DONE")
})
function initTTY(port) {
tty = new SerialPort(port)
tty.on('data', () => {
// Do something here
})
tty.on('error', () => {
tty = null; // so that can initialized
})
}
You can do something like this.你可以做这样的事情。
let tty = undefined;
// Your business logic...
app.post('/submit-port', (req, res) => {
tty = new SerialPort(req.body.portpath);
tty.on('data', () => { /* TODO: implement the handler */ });
});
You can consider the endpoint an "initializer" for your tty client.您可以将端点视为 tty 客户端的“初始化程序”。 Now you're sure that your instance is initialized before using it.
现在您确定您的实例在使用之前已初始化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.