【问题标题】:Unable to add elements in array无法在数组中添加元素
【发布时间】:2021-04-21 10:19:06
【问题描述】:

我正在尝试在我的电脑上添加可用端口,用于 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);

代码的输出为:

【问题讨论】:

  • SerialPort.list() 是异步的。您的 console.log 在它之前执行,因此数组仍然是空的。
  • 那么如果 serialPort.list() 是异步函数,如何在数组中添加元素。

标签: javascript node.js arduino serial-port node-serialport


【解决方案1】:

试试这个:

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

【讨论】:

    【解决方案2】:

    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();
    

    【讨论】:

      猜你喜欢
      • 2014-05-06
      • 1970-01-01
      • 2013-06-06
      • 1970-01-01
      • 1970-01-01
      • 2018-02-27
      • 1970-01-01
      • 2018-07-02
      相关资源
      最近更新 更多