繁体   English   中英

无法在数组中添加元素

[英]Unable to add elements in array

我正在尝试在我的电脑上添加可用端口,用于 Arduino 和电脑之间的串行通信。 我已将 portsList 创建为数组变量,并将这些端口推送到该变量中。 但最后,我得到的数组长度为 0。我使用的是串口节点模块。

const SerialPort = require("serialport");

var portsList = [];
SerialPort.list().then((ports) => {
  ports.forEach((port) => {

    var portInfo = {
      portPath: port.path,
      portManufacturer: port.manufacturer,
    };

    portsList.push(portInfo);
    console.log("Port: ", portInfo);
  });
});

console.log(portsList.length);

代码的output为: 这里

尝试这个:

    portsList.push({
      portPath: port.path,
      portManufacturer: port.manufacturer,
    });
    console.log("Port: ", portInfo);

SerialPort.list() 似乎是异步的。 将控制台放在“forEach”之后

const SerialPort = require("serialport");

var portsList = [];
SerialPort.list().then((ports) => {
  ports.forEach((port) => {

    var portInfo = {
      portPath: port.path,
      portManufacturer: port.manufacturer,
    };

    portsList.push(portInfo);
    console.log("Port: ", portInfo);
  });
  console.log(portsList.length);
});

或等待列表,

const SerialPort = require("serialport");
     
const getPortsList = async () => {
  var portsList = [];
  const ports = await SerialPort.list();

  ports.forEach((port) => {

    var portInfo = {
      portPath: port.path,
      portManufacturer: port.manufacturer,
    };

    portsList.push(portInfo);
    console.log("Port: ", portInfo);
  });

  console.log(portsList.length);
}

getPortsList();

暂无
暂无

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

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