Function within JQuery what is the order of execution?

4

I have a function in jquery that has a while that writes data to the database, and after this while it prints to console that the data has been saved, the function looks like this:

function gravaDados(){
var qtde_linhas = 6 //ele pega a quantidade de linhas da tabela a ser salvo
var x = 1;
while( x <= qtde_linhas ) {

    ...//dados AJAX
    ... console.log('Dados gravados'); //salva os registros

x++;
}
console.log('dados salvos com sucesso '+x);
}

On the console it appears that the data has been saved and the current position of the x is 7, ie it saved the 6 lines in the database, but my question is the following because the console.log from within while is printed last ?

As seen in the image it writes the data but prints the console in reverse, this is due to the delay of recording the data in the database, or if I insert another function in place of the last console I can have problems the data do not have finished and perform the other function? For now it is working, but I have this doubt, or is there a way to check if the while is finished to continue with the structure?

    
asked by anonymous 02.10.2017 / 13:56

3 answers

4

This is probably because the console that is inside while is also within callback of ajax, which is asynchronous.

In other words, the code triggers the ajax requests to save to the database, exits the while, and runs the console that is following the while. Later (though only milliseconds) the bank's responses begin to arrive and fire up their console.log .

In these cases it is even possible that console.log within the while arrives with a changed command, ie not in the exact sequence they were "fired."

    
02.10.2017 / 14:00
3

Because ajax code execution is by default asynchronous, that is, jquery will not wait for the execution of its routine to save the data in the database before giving the console.log of "Data saved successfully".

I imagine that's your problem.

Here is a slightly more detailed explanation. link

    
02.10.2017 / 14:02
2

Fernando Wagner, another thing that was not informed, is that the first function can not have "-" (dash). This can be done for example:

gravaDados() 

And <= can not also have space < =

function gravaDados(){
    var qtde_linhas = 6 //ele pega a quantidade de linhas da tabela a ser salvo
    var x = 1;
    while ( x <= qtde_linhas ) {
        console.log('Dados gravados'); //salva os registros
        x++;
    }
    console.log('dados salvos com sucesso '+x);
}
gravaDados();

Another thing is that I do not know why it was printed last, but here it was in normal order, with the above code:

    
02.10.2017 / 14:05