Calling a function when another ends

Asked

Viewed 37 times

0

I need to call a function in jQuery, but it has to wait for another function to finish, because it depends on the result of the first function to work. I’m using the jQuery.

Follow the first passage:

$(function(){
    $('#id_gestora').each(function(){
        if( $(this).val() ) {
            $('#id_projeto').hide();
            $('.carregando').show();
            $.getJSON('_model/popularprojeto_gestoraprojeto.php?search=',{id_gestora: $(this).val(), ajax: 'true'}, function(j){
                var options = '<option value="">Selecione um projeto</option>'; 
                for (var i = 0; i < j.length; i++) {
                    options += '<option value="' + j[i].id_projeto + '">' + j[i].descricao_projeto + '</option>';
                }
                $('#id_projeto').html(options).show();
                $('#id_projeto').val('<?php echo $projeto_calendariocontabilfundo_edit; ?>');
                $('.carregando').hide();
            });
        } else {
            $('#id_projeto').html('<option value="">Selecione um projeto</option>');
            $('#id_projeto').show();
        }
    });
});

And the second, which depends on the previous:

$(function(){
    $('#id_projeto').each(function(){
        if( $(this).val() ) {
            $('#id_calendariocontabil').hide();
            $('#id_calendariocontabil').html('<option value=""></option>');
            $.getJSON('_model/popularcalendariocontabil_projeto.php?search=',{id_projeto: $(this).val(), ajax: 'true'}, function(j){
                $('#id_calendariocontabil').show();
                var options = '<option value="">Selecione um </option>';    
                for (var i = 0; i < j.length; i++) {
                    options += '<option value="' + j[i].id_calendario + '">' + j[i].descricao_calendario + '</option>';
                }   
                $('#id_calendariocontabil').html(options).show();
                $('#id_calendariocontabil').val('<?php echo $calendario_calendariocontabilfundo_edit; ?>');
                $('.carregando').hide();
            });
        } else {
            $('.carregando').hide();
            $('#id_calendariocontabil').html('<option value="">Selecione um calendário contábil</option>');
        }
    });
});

1 answer

1


As you are dealing with asynchronous processing, a good option for your case is to utilize callbacks. Just create two functions, making one of them receive one callback.

Basically, you can do something like this:

first(function() {
  second();
  // Chame outras funções aqui...
});

function first(callback) {
  console.log('Função `first` invocada.');

  setTimeout(function () {
    console.log('Chamando o callback...');
    callback();
  }, 1500);
}

function second() {
  console.log('Função `second` invocada.');
}

To learn more about how the callbacks work, see this other question.

So in your code, you could do something like this:

$(function () {
  gestora(projeto);
});

function gestora(callback) {
  $('#id_gestora').each(function () {
    if ($(this).val()) {
      $('#id_projeto').hide();
      $('.carregando').show();
      $.getJSON('_model/popularprojeto_gestoraprojeto.php?search=', {
        id_gestora: $(this).val(),
        ajax: 'true'
      }, function (j) {
        var options = '<option value="">Selecione um projeto</option>';
        for (var i = 0; i < j.length; i++) {
          options +=
            '<option value="' +
            j[i].id_projeto +
            '">' +
            j[i].descricao_projeto +
            '</option>';
        }
        $('#id_projeto').html(options).show();
        $('#id_projeto').val(
          '<?php echo $projeto_calendariocontabilfundo_edit; ?>'
        );
        $('.carregando').hide();

        // Chamar o callback após o sucesso de `getJSON`. Este é assíncrono:
        callback();
      });
    } else {
      $('#id_projeto').html('<option value="">Selecione um projeto</option>');
      $('#id_projeto').show();

      // Chamar o callback no caso do `else`:
      callback();
    }
  });
}

function projeto() {
  $('#id_projeto').each(function () {
    if ($(this).val()) {
      $('#id_calendariocontabil').hide();
      $('#id_calendariocontabil').html('<option value=""></option>');
      $.getJSON('_model/popularcalendariocontabil_projeto.php?search=', {
        id_projeto: $(this).val(),
        ajax: 'true'
      }, function (j) {
        $('#id_calendariocontabil').show();
        var options = '<option value="">Selecione um </option>';
        for (var i = 0; i < j.length; i++) {
          options +=
            '<option value="' +
            j[i].id_calendario +
            '">' +
            j[i].descricao_calendario +
            '</option>';
        }
        $('#id_calendariocontabil').html(options).show();
        $('#id_calendariocontabil').val(
          '<?php echo $calendario_calendariocontabilfundo_edit; ?>'
        );
        $('.carregando').hide();
      });
    } else {
      $('.carregando').hide();
      $('#id_calendariocontabil').html('<option value="">Selecione um calendário contábil</option>');
    }
  });
}

Another option is to use an object Deferred jQuery, which is similar to a Promise of Ecmascript 2015, but for this case I believe it is too.

An important addition is that if you are working with newer versions of Ecmascript, use callbacks can be seen as a anti-pattern, since this pattern provides the emergence of some problems and there are more modern resources to manage the chaining of asynchronous processes, such as Promises.

  • Thank you very much Luiz Felipe, it worked correctly, vlw by force... Saw if I need to call one more Function along with the second. Ex.: we continue with the same scenario, the first wheel Function, as soon as it finishes we are running the second... Could it run a third Function along with the second? can be at the same time as the second.

  • 1

    In this case you pass an anonymous function as callback and calls the second and third inside that anonymous. I edited the question...

  • If I understand correctly, create a Function with a generic name, put the second and third Function within this generic function... Oh yes I call that generic Function in callback. Would that be?

  • It worked, kkkk

  • 1

    Luiz Felipe, thank you very much bro... Very fast and effective. Gave bless your day.

Browser other questions tagged

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