2

I have to iterate over an array inside an async funtion. The function does not seem to terminate at the resturn statement but continues further.

I am using:

async function f(args){
...
...
...

arr.forEach((z) => {
    if (condition) 
    {
        console.log("Should be true");
        return true;
    }
});
console.log("Should not reach here");
return false;
}

When I call the function with, the console has both the statements logged while the value returned is false when it must be true.

const res = await f(args);
console.log("RES: ", res);
Should be true
Should not reach here
RES: false;

The same thing happens if I use map.

1 Answers1

0

You are returning true from the fat arrow function you are sending through to forEach and not your f function. The false return statement returns your f function since it is not inside the block scope of the forEach function.

Use some instead of forEach, since the return statement inside your forEach will not affect your wrapping function.

some will return if the statement return true, otherwise if it gets throug all elements it will return false, and then you can return that in your wrapping function. Think of it as a "does this exist in the array"-function.

async function f(args) {
  ...
  ...
  ...

  return arr.some((z) => {
    if (condition) {
      console.log("Should be true");
      return true;
    }
  });
}
Nils Kähler
  • 2,645
  • 1
  • 21
  • 26