0

So I got this code to get the correct COM name:

//serialport lib import
var serialport = require("serialport");

//global var
var prt;

serialport.list(function (err, ports) {
  ports.forEach(function (port) {
    //this does NOT work.
        prt = port.comName);
      });
    });

console.log(prt); //outputs UNDEFINED

The problem is that wherever I try to set prt to some value inside the .list()'s scope. It doesn't set the variable.

I can however call global functions. Which really doesn't make any sense to me.

//serialport lib import
var serialport = require("serialport");

//global var
var prt;

//global function
var printPort = function(port){
  console.log(port);
}

serialport.list(function (err, ports) {
  ports.forEach(function (port) {
    //this does NOT work.
    prt = port.comName);
    //and this DOES
    printPort(port.comName); //outputs "COMx"
  });
});

I now that this is a scope related problem of course. I'm quite new to this, and quite confused about this behaviour. The fact that I can call the global function BUT I can't set the global variable doesn't make any sense to me.

Another last question would be how to make a function out of this that RETURNS the port name. Since it's async I can't return it.

Thank you very much.

  • It *does* set the variable. This is not a scope problem. It's about timing! – Bergi Mar 04 '16 at 01:19
  • Thank you for your answer. What is the correct way to go about this then? – Kevin Johansson Mar 04 '16 at 01:22
  • You've got the solution already: call a callback. You cannot make a function that `return`s the port name. – Bergi Mar 04 '16 at 02:03
  • Ok but how can GET the value? How can I pass it to the global variable? – Kevin Johansson Mar 04 '16 at 02:24
  • You CANT (or shouldn't). Wherever you want to use the value, you will need to account for the fact that it is only asynchronously available - and use callbacks. You can store a promise for the value in the global variable. – Bergi Mar 04 '16 at 04:27

0 Answers0