1

I have a method with a forEach loop.

This works fine and shows a result list.

Here is the code:

test() {

  os.cpus().forEach(el => {
    if (el.model.search('Intel') === 0) {
      return el.model.match(/i(.*)-/)[1];
    }
  });

}

The forEach has a return and the method return undefined.

I know I need to do a callback but I just don't know how to do this in this code.

How can I get test() to return the result?

  • Possible duplicate of [Callback after all asynchronous forEach callbacks are completed](https://stackoverflow.com/questions/18983138/callback-after-all-asynchronous-foreach-callbacks-are-completed) – xerx593 Feb 11 '19 at 01:09

1 Answers1

2

Use .find instead, and if a match is found, perform the .match( operation:

test() {
  const foundEl = os.cpus().find((el) => el.model.search('Intel') === 0);
  if (foundEl) {
    return foundEl.model.match(/i(.*)-/)[1];
  }
}

Since it looks like el.model is a string, better to use startsWith than .search:

test() {
  const foundEl = os.cpus().find((el) => el.model.startsWith('Intel'));
  if (foundEl) {
    return foundEl.model.match(/i(.*)-/)[1];
  }
}

You generally have to use callbacks for asynchronous operations. With synchronous operations (such as this one), you can simply return the value.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320