sun only refreshes at end of event

1

Hello,

I have a button with a click event, and when I click on it, I make an ajax request in a foreach. I would like to open a loading mode to run while the requests are being made, but the modal only opens when they all finish and the event ends.

$(document).ready(function(){
                $('#loading').modal();

                var contadorEnviados = 0;
                var contadorErros = 0;

                $('#botao').click(function(event){
                     event.preventDefault();
                     $('#loading').modal('open');
                     var emails = $('#emails').val().split("\n");

                     emails.forEach(function(email){
                          if(fazRequisicao(email)){
                               contadorEnviados++;
                          }
                          else{
                               contadorErros++;
                          }
                          atualizaContadores(contadorEnviados,contadorErros);
                     });

                     inicializaContador();
                     $('#loading').modal('close');
                });

           });

function doRequisition

function fazRequisicao(email){
  $.get("teste.php", {email: email}, function(resposta){
      return resposta;
 });

}

    
asked by anonymous 10.08.2017 / 15:44

1 answer

0

This fazRequisicao function does not give synchronous feedback. return resposta; has no effect for if(fazRequisicao(email)){ . In other words, forEach runs to the end before even the first fazRequisicao respond (you can read more here You have to change logic.

You can do this with Promisses, so you are sure that all functions have been called and answered.

Change your role to:

function fazRequisicao(email) {
  return new Promise(function(resolve, reject) {
    $.get("teste.php", {email: email})
      .done(resolve)
      .fail(reject);
      .always(function(xhr, status, deferred) {
        if (deferred.isResolved()) contadorEnviados++;
        else contadorErros++;
        atualizaContadores(contadorEnviados, contadorErros);
      });
  });
});
}

and then you can use Promise.all that waits for all requestions:

$('#botao').click(function(event) {
  event.preventDefault();
  $('#loading').modal('open');
  inicializaContador();
  var emails = $('#emails').val().split("\n");
  Promise.all(emails.map(fazRequisicao)).then(function(respostas) {
    $('#loading').modal('close');
  ));
});
    
10.08.2017 / 16:21