过滤从 Promise 返回的数组

Filtering an array returned from Promise

我正在移植以下代码:

function FindDevices() {
  let ports = portLister.list();
  let devices = []
  for (port of ports) {
    try {
      device = new Device(port); // throws if not valid port
      devices.push(device);
    }
    catch {
      // log(port); 
    }
  }
  return FindDevices;
}

当前版本应使用 SerialPort.list(),即 returns a promise

到目前为止,我尝试了这些方法,但没有成功:

const SerialPort = require('serialport');

async function FindDevices() {
  const result = (await SerialPort.list()).filter(port => new Device(port));
  return result;
}

FindDevices().then(devices => {
  console.log(devices);
});

显然我没有完全明白我应该做什么。所以问题是:我应该如何使用 async/await 或 Promises 表示前 FindDevices 函数的相同意图? 消费结果的好方法是什么?例如,我应该如何获取第一个找到的设备?

为什么不使用相同的函数而是使用 await?

async function FindDevices() {
  const ports = await SerialPort.list();
  const devices = [];
  for (let port of ports) {
    try {
      const device = new Device(port); // throws if not valid port
      devices.push(device);
    } catch {
      // log(port); 
    }
  }
  return devices;
}

只需等待 SerialPorts 的解析器执行所有操作,并在需要时使用您的设备解析 Promise

function portListener() {
  this.list = function() {
      return Promise.resolve([80,443,4200,4300]);
  }
}

class Device
{
  constructor(port)
  {
    this.port = port;
  }
}

async function FindDevices() {
    var devices = [];
    await new portListener().list().then(function(ports) {
    for (port of ports) {
      try {
        device = new Device(port); // throws if not valid port
        devices.push(device);
      }
      catch {
        // log(port); 
      }
    }
  });
  return Promise.resolve(devices);
}

FindDevices().then(function(devices) {
  console.log(devices);
});

我认为您确实需要根据失败过滤项目,因此您可以在映射器中添加 catch 块,然后过滤出结果

async function FindDevices() {
  const ports = await SerialPort.list();
  const results = ports.map(port => {
    try {
      return new Device(port)
    } catch() {
      return null
    }
  }).filter(port => !!port);

  return results;
}