How do i use function if i need to define it later?

Viewed 56

So, I'm using node.js, express and serialport. 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. But I can't actually initizalize SerialPort object somewhere in the middle of the code, because it starts raining with "is not defined" errors. 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. And I understand this logic - I haven't initialized that object before, so, how could I do it? 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. What am I supposed to do in order to make it work?

2 Answers

You need lazy init and singleton, then this solution can be used.

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. Now you're sure that your instance is initialized before using it.

Related