Logic with callback

Asked

Viewed 140 times

2

I am with a small problem and I would like a help to understand and if possible an indication from Srs to help this problem.

Let’s start, currently I have a loop, I’m doing it in a been getting something like the code below:

for(var i = 0; i < 1500; i++){
 console.log("Valor "+i);
}

Within this loop I am calling a function that is updating some information, and in this same function I am using callback at the end. (by my understanding the callback would be to give kind of a pause in the code and it will only continue if there is the right callback? ) The code is below

var Anonimo = {

  minhaFuncao: function(indice,callback){
    //faz algumas coisas

    //finaliza com callback
    callback(retornaAlgumaVariavel);
  }

}

So far beauty.. My complete code so far was as follows:

var Anonimo = {

  minhaFuncao: function(indice,callback){
    //faz algumas coisas

    //finaliza com callback
    callback(retornaAlgumaVariavel);
  }

}


for(var i = 0; i < 1500; i++){
 console.log("Valor "+i);

 Anonimo.minhaFuncao(i, function(variavelRetorno){
  console.log("Entrou no indice "+i);
 });
} 

by my debug is having the output correctly it would be, every loop input is running callback.. Example

Valor 1
Entrou no indice 1
Valor 2
Entrou no indice 2
[....]

The problem is being in the following item... when I call the "myFuncao" I pass the callback that is to execute something when finlizar the execution of it, in this case I am passing another function that also has a callback... something like this:

var OutroAnonimo = {

  outraFuncao: function(callback){
    //faz algumas coisas

    //finaliza com callback
    callback();
  }

}

My complete code is as follows:

for(var i = 0; i < 1500; i++){
 console.log("Valor "+i);

 Anonimo.minhaFuncao(i, function(variavelRetorno){
  console.log("Entrou no indice "+1);

  OutroAnonimo.outraFuncao(function(){
    console.log("Passou aqui...");
  });
 });
}

The error is in the following item, in the Loop, I go through the first and second console.log but when I call "otherFuncao" it is ignored, better explaining, the loop repeat 1500 times, in the debug comes out the message "Valor e Entrou no indic..." but after that passed 1500 times appears the messages "Passed here".

My final doubt is, what did I do wrong? or what do I do to make it better? I need you to do it this way...

The loop starts at 0, calls the function "myFunction" after it is finished calls the "otherFuncao" after it has finished I go to position 1, 2, and so on.

1 answer

2


That’s the same problem of this question/answer. That is, when this callback is called (a time that is asynchronous) the loop is over and the i value has changed in the meantime. So when you use i inside the callback the variable is no longer what you think. There is another case related here.

In your case you can solve it simply once you’re through the i for the method Anonimo.minhaFuncao. Now if you use that i that was "consumed" by the function so you can pass it back on the callback so:

var Anonimo = {

  minhaFuncao: function(indice, callback){
    //faz algumas coisas

    //finaliza com callback
    callback(indice, retornaAlgumaVariavel);
  }

}

and in the loop use:

for(var i = 0; i < 1500; i++){
 console.log("Valor " + i);

 Anonimo.minhaFuncao(i, function(indice, variavelRetorno){
   console.log("Entrou no indice " + indice);

If you want to force everything to happen sequentially you can do so:

function processar(arr) {
    if (arr.length == 0) return;
    var nr = arr.shift(); // e aqui encurta ao mesmo tempo a array
    console.log("Valor " + nr);
    Anonimo.minhaFuncao(nr, function(ind, variavelRetorno) {
        console.log("Entrou no indice " + ind);
        OutroAnonimo.outraFuncao(function() {
            console.log("Passou aqui... e terminou o indice", ind);
            processar(arr);
        });
    });
}

// para gerar o conteudo
var valores = [];
for (var i = 0; i < 15; i++) {
    valores.push(i);
}
processar(valores);

jsFiddle: https://jsfiddle.net/afgbmm7u/

Browser other questions tagged

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