1

I have a the below code, on which i am unable to break the loop on certain conditions.

Expected Result : Error message should appear and user should be able to close the message and remove the escalation node properly

Actual Result : User Cannot remove the Error message by clicking ok..it automatically disappear within several minutes

public findVerticesBelow(vertexId: number) {
    // debugger
    this.recussionTime++;
    if(this.recussionTime <= 150){
        console.log(this.recussionTime)
        if (!this.vertexIdList.includes(vertexId)) {
            this.vertexIdList.push(vertexId)
          }
          let tempvertexIdList: Array<number> = new Array<number>();
          this.edges.forEach(edge => {
            if (edge.fromId == vertexId) {
              tempvertexIdList.push(edge.toId);
            }
          })

          tempvertexIdList.forEach(tempvertexId => {
            this.findVerticesBelow(tempvertexId)
          });
    }else{
        // debugger
        console.log("AAAAAAAAAAAAAAA")
        // alert("You are having a recursive loop please remove it before trying to remove nodes")
        // alert("ASCDFVGBHN")
    }
  }

I want to break the code and return the boolean value, but I am unable to do it right now. Can anybody help me.

qwertyuio
  • 159
  • 3
  • 9

3 Answers3

1

This is not proper way but you can use it

let a=[1,2,3,3,4,4,4];
try{
   a.forEach((x,y)=>{
    console.log(x);
    if(x==4){
       throw "break";
    }
   })
}catch(e){
console.log(e);
}
kelvin kantaria
  • 1,438
  • 11
  • 15
-1

You cann't stop the forEach loop in any JavaScript or TypeScript file. If want to use break you can simply use the for loop. If you want to learn more click here!

-1

It is not possible to break from forEach normally.Use the for loop instead of forEach.

There are 3 things which you might have not known about the forEach loop.

  1. "return" doesn’t stop looping.
  2. You cannot ‘break’.
  3. You cannot ‘continue’.

Read more : https://medium.com/front-end-weekly/3-things-you-didnt-know-about-the-foreach-loop-in-js-ff02cec465b1

Or

you can use Array.every() if you wish to return false while breaking the loop.

If you want to return true, then you can use Array.some()