Stop loop in function inside another

1

Good morning, I'm starting on nodejs. I need to make a function that is called inside the other go back to my loop, however I'm having difficulty with this. Segua down the code I made. From loop to function test2 and from test2 to test3 and from test3 rec

 var teste3 = function teste3(n){
    if (n == 2 || n == 4) {
        console.log("chego na 3")
        return;
    };
}

var teste2 = function teste2(n, callback){
    if (n == 1 || n == 5) {
        console.log("chego no 2")
    }else if (n == 2 || n == 4){
        callback(n);
    }
}
var i = 0;
var teste = function teste(){
    while(i < 10){
        teste2(i, teste3);
        console.log(i);
        i++
    }
}
teste();
    
asked by anonymous 10.07.2015 / 16:59

2 answers

2

I do not understand what your code problem is, but to stop the loop, you can use: break; or return your method with return; .

    
10.07.2015 / 18:19
4

If the goal is to break the loop if you enter if of teste3 , not a return is inside that function. The return would need to be inside the teste function, because the functions do not return "cascading". Another way to break a loop is to use break . I would rewrite your code like this:

var teste3 = function teste3(n){
    if (n == 2 || n == 4) {
        console.log("chegou na 3")
        return true;
    };
}

var teste2 = function teste2(n, callback){
    if (n == 1 || n == 5) {
        console.log("chegou no 2")
    }else if (n == 2 || n == 4){
        return callback(n);
    }
}
var i = 0;
var teste = function teste(){
    while(i < 10){
        if(teste2(i, teste3)) {
           console.log('saindo do loop');
           break; 
        }
        console.log(i);
        i++;
    }
}
teste();
    
10.07.2015 / 17:52