How to wait for the previous function to create the component on the screen and then take the data from that component (javascript)

Asked

Viewed 41 times

2

Good morning, I’m having trouble getting the values of a select Box from my screen, the situation is as follows, I create the page normally with the default values in select Box ex: Carrying... because based on the permissions of the user he will be able to change the value of Select Box or not, finally first I run a function that arrow the values in select Box and the function then takes the value of this select Box to make queries to the bank, the problem is that the second function takes the default values Carrying... and not the value that I set it happens because the second function takes the value before the first function recreate the correct component, I tried to use a setTimeOut to wait a couple of seconds to then perform the second function, in this case it worked but seemed to me gambiarra, so I tried to use a Promise but the Promise returned positive even though I didn’t really finish building the component. follows my code: html:

  </div>
      <div class="row">
        <div class="col-xl-3 col-md-3 col-sm-12 mb-4">
          <div class="input-group mb-3" id="divSelectPacotes">
            <select class="custom-select" id="selectPacotes">
              <option value="0" selected >PACOTE</option>
            </select>
          </div>
        </div>
        <div class="col-xl-3 col-md-3 col-sm-12 mb-4">
          <div class="input-group mb-3" id="divSelectDepartamentos">
            <select class="custom-select" id="selectDepartamentos">
              <option value="0" selected>DEPARTAMENTO</option>
            </select>
          </div>
        </div>
        <div class="col-xl-3 col-md-3 col-sm-12 mb-4">
          <div class="input-group mb-3" id="divSelectFilial">
            <select class="custom-select" id="selectFilial">
              <option value="0" selected>FILIAL</option>
            </select>
          </div>
        </div>
        <div class="col-xl-3 col-md-3 col-sm-12 mb-4">
          <div class="input-group mb-3" id="divSelectMes">
            <select class="custom-select" id="selectMes">
              <option value="0" selected>MÊS</option>
            </select>
          </div>
        </div>
      </div>

Javascript:

$(document).ready(function () {
comboBox(); //Seta os valores nos select Box
cards();  // Executa consulta no banco com parametros retornado do select Box
tabela(); // Executa consulta no banco com parametros retornado do select Box
graficoMetaPacote(); // Executa consulta no banco com parametros retornado do select Box
graficoComparaPacote(); // Executa consulta no banco com parametros retornado do select Box

});

I found a function I can’t tell if it was the right way to go: was calling the other functions within the first, thus:

function comboBox() {
    pageurl = 'consultas/sql/comboBox.php';
    $.ajax({
        url: pageurl,
        type: 'GET',
        cache: false,
        dataType: 'json',
        error: function (result) {
            console.log('erro ao trazer os valores nos comboBox\n' + result);
        },
        success: function (result) {

            // console.log(result);
            var resultado = [];
            for (var i in result) {
                resultado.push(result[i]);
            }
            //Trás os valores para os select Box ==========================================================
            $("#divSelectPacotes").html(resultado[0]);
            $("#divSelectDepartamentos").html(resultado[1]);
            $("#divSelectFilial").html(resultado[2]);
            $("#divSelectMes").html(resultado[3]);
            
            cards();  // Executa consulta no banco com parametros retornado do select Box
            tabela(); // Executa consulta no banco com parametros retornado do select Box
            graficoMetaPacote(); // Executa consulta no banco com parametros retornado do select Box
            graficoComparaPacote(); // Executa consulta no banco com parametros retornado do select Box
        }
    })
   
};

If anyone has a better idea please let me know, Thank you!

  • 2

    by ajax being async the best option is to put the other functions within the same Success, or else disable the ajax async (not recommended)

1 answer

2


If you are making a request it is necessary to wait for the server response to perform the other operations since they need this data, so Synchronous, and you’ve done it with the .ajax() and the callback Success

Another way would be for you to have used the return of Promise of .ajax() and created a chain with the other object methods jqXHR, which is not a native Promise, but keeps the interface.. May have done so:

$.ajax({url: 'consultas/sql/comboBox.php', cache: false, dataType: 'json'})
    .then((result) => { 
        // Outras consultas
    }, () => console.log('erro ao trazer os valores nos comboBox'))

The subsequent functions carry out the other queries in such a way Asynchronous, are placed in the Event and executed soon when the browser can, and because there is no barrier or flow in those calls then they are not necessarily returned in the same order..

cards();
tabela();
graficoMetaPacote();
graficoComparaPacote();

Async/sync

Another way you could have defined these calls would be by creating asynchronous functions, would be executed in a blocking manner, one after the other in the same order:

cards().then(tabela).then(graficoMetaPacote).then(graficoComparaPacote).catch(console.log)
// ou outra função async a qual as executa com await
async function preencherDados() {
    await cards()
    await tabela()
    await graficoMetaPacote()
    await graficoComparaPacote()
}
preencherDados().catch(console.log)
  • show many thanks already solved up my other previous problems!

Browser other questions tagged

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