Javascript does not follow the algorithm flow

Asked

Viewed 60 times

0

Example :

$("#segundaFeira").change(function(){
        valorSegundaFeira = calcularJornadaDeTrabalho(this.value);
        var x = valorFinalJornadaTrabalho();
        alert(x);
});

Note that the global variable valorSegundaFeira is defined by a function that returns a value. so far so good the problem that when I call change is printing the alert(x) first to enter the function calcularJornadaDeTrabalho and define the value of valorSegundaFeira. I don’t know why you’re not following the structured algorithm.

HTML code

<select class="form-control" th:field="*{segundaFeira}" >
                option value="" selected="selected">--</option>
                <option th:each="horario : ${listaHorarioTrabalhoDiario}" th:value="${horario.id}"
                                            th:text="${horario.descricao}">horario</option>
</select>

Function calculatorJornadaDework

function calcularJornadaDeTrabalho(value){
        var **= 440;
        var **= 528;
        var **= 480;
        var **= 540;
        var **= 480;
        var **= 240;
        var **= 360;
        var valorTotal = 0;
        var **= 0;

        $.get(urlJornadaTrabalho, {idHorario: value}).done(function (horario) {
            **= horario.**; 
            if (**== '**') {
                valorTotal = **;
            }
            if (**== '**') {
                valorTotal = **;
            }
            if (**== '**') {
                valorTotal = **;
            }
            if (**== '**') {
                valorTotal = **;
            }
            if (**== '**') {
                valorTotal = **;
            }
            if (**== '**') {
                valorTotal = **;
            }
            if (**== '**') {
                valorTotal = **;
            }
            alert("vlrTotal " + valorTotal);
        }).fail(function(xhr) {
            console.log("erro ao fazer ajax na urlJornadaTrabalho");
        });
        return valorTotal;
    }
  • Could you please show us the HTML as well?

  • Put to calculatDeworking() also.

  • OK just a moment

  • I’ve already made the edits

  • you use some framework/library js without being jquery ?

  • @Gabrielrodrigues not only jquery

  • @Josevieiraneto the AJAX calculatedDework is done whenever the event change occurs?

  • @flpms yes is done every time I call the change event but I realized he’s not getting into the $.Get on the first call is like if underneath the scenes he calls himself twice doing q the first time the value is 0

  • I’ll edit my answer with something that might help you.

  • You can edit the question with the basic implementation of the value?

  • @flpms this function it only makes the sums of the global variables ex : valueFeira + valueTercaFeira

Show 6 more comments

3 answers

2

The @flpms response already answers why this does not work, you are working with Names and before waiting for the request to return and the Password to be solved you already return the variable that is still without the calculation value.

Try the following solution:

$("#segundaFeira").change(function() {
  calcularJornadaDeTrabalho(this.value).done(function(varloRetornadoPromise) {
    valorSegundaFeira = varloRetornadoPromise;
    var x = valorFinalJornadaTrabalho();
    alert(x);
  }).fail(function(error) {
    console.dir(error);
  });

});

function calcularJornadaDeTrabalho(value) {
  var * *= 440;
  var * *= 528;
  var * *= 480;
  var * *= 540;
  var * *= 480;
  var * *= 240;
  var * *= 360;
  var valorTotal = 0;
  var * *= 0;

  return $.get(urlJornadaTrabalho, {
    idHorario: value
  }).done(function(horario) { * *= horario.* * ;
    if ( * *= = '**') {
      valorTotal = * * ;
    }
    if ( * *= = '**') {
      valorTotal = * * ;
    }
    if ( * *= = '**') {
      valorTotal = * * ;
    }
    if ( * *= = '**') {
      valorTotal = * * ;
    }
    if ( * *= = '**') {
      valorTotal = * * ;
    }
    if ( * *= = '**') {
      valorTotal = * * ;
    }
    if ( * *= = '**') {
      valorTotal = * * ;
    }

    return valorTotal;
  }).fail(function(xhr) {
    return "erro ao fazer ajax na urlJornadaTrabalho";
  });

}

I recommend a bit of study on Precedents and their implementations in javascript so you can perfectly understand the flow of code above.

  • I forgot the Promisses approach, I was so focused on explaining why I forgot that hand on the wheel.

1

Your problem is in the asynchronous part of Javascript.

When the event occurs change the function calcularJornadaDeTrabalho did not complete the execution. Then the variable valorSegundaFeira is undefined.

Suggestion is that you fix the global scope execution and in the event callback change you call the action that fills the variable valorSegundaFeira with the information you want.

You can pass the function valorFinalJornadaTrabalho as callback, at the end of the call from calcularJornadaDeTrabalho. The call would look like this:

calcularJornadaDeTrabalho(value, valorFinalJornadaTrabalho) {
    //Após o sucesso do AJAX
    valorFinalJornadaTrabalho(valores);
}

The Javascript is different from other languages, it does not have a step-by-step execution, it can execute an AJAX while you do not even have the answer yet perform the sum of values. So to ensure the execution step by step you use the callback, the action that must be called after the end of the previous execution.

0

Your GET call is running synchronously and until its output the subsequent functions have already been executed.

I suggest you use the GET call as follows (async false):

$.ajax({
    url : urlJornadaTrabalho,
    type : "get",
    async: false,
    data: {idHorario: value},
    success : function(horario) {
        * *= horario.* * ;
    if ( * *= = '**') {
      valorTotal = * * ;
    }
    if ( * *= = '**') {
      valorTotal = * * ;
    }
    if ( * *= = '**') {
      valorTotal = * * ;
    }
    if ( * *= = '**') {
      valorTotal = * * ;
    }
    if ( * *= = '**') {
      valorTotal = * * ;
    }
    if ( * *= = '**') {
      valorTotal = * * ;
    }
    if ( * *= = '**') {
      valorTotal = * * ;
    }

    return valorTotal;
    },
    error: function() {
       return "erro ao fazer ajax na urlJornadaTrabalho";
    }
 });
  • I wouldn’t recommend this @Iago approach. You block any other user action during the request. Approaches with Promises or using callback in general are better by not causing the lock.

Browser other questions tagged

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