Skip to content
Advertisement

Filtering an array returned from Promise

I am porting the following code:

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;
}

Current version should use SerialPort.list(), which returns a promise.

So far, I tried something along these lines, without success:

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

Obviously I am not quite getting what I should do. So the question is: how should I represent the same intent of former FindDevices function, using async/await or Promises? And what would be a good way of consuming that result? For example, how should I get the first found device?

Advertisement

Answer

I think you do need to filter items based on failure, so you can add catch block in mapper and then filter out the results

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;
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement