Stop loop in function inside another

Asked

Viewed 219 times

1

Good morning, I’m starting on nodejs. I need to get one function that is called inside the other back into my loop, but I’m having a hard time with that. Follow below the code I made. From loop to teste2 and teste2 to teste3 and teste3 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();
  • What’s the problem? This code seems to be working normally.

  • The goal is to stop the loop if you enter the if of teste3?

  • My goal is to go back to the loop and continue it, this question was just an example, if you had another if in test3 not to make var test3 = Function teste3(n){ if (n == 2 || n == 4) { //return to the loop without doing the next if console.log("I arrive at 3") Return; }; if(n == 0){ } }

2 answers

4

If the goal is to break the loop if you enter the if of teste3, not enough a return inside that function. The return would need to be inside the function teste, because the functions do not return "cascading". Another way to interrupt a loop is to use break. I’d 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();

2


I don’t understand what’s wrong with your code, but to stop the loop, you can use: break; or return your method with return;.

  • Now I understand, I am working with Node and mongodb, in case, I have a queue of things to do where they go calling various functions through the callbacks. But in some cases in a certain function I need to return to my loop that is in the initial function.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.