JavaScript function does not wait for another to finish before starting

Question:

Problem

My function is not waiting for the other one to finish so it can continue, for example:

Example:

function buscando_dados(){
   $.post('ajax.php',{},function(dados){
      alert(dados); 
   });
}
function buscar_dados(){
   buscando_dados();
   alert('prosseguindo'); //Prosseguindo está função sem esperar a outra acabar a requisição
} 

I don't know how to make the alert('prosseguindo'); be executed only after alert('dados'); and at the moment this is not happening.

How can I do this?

Answer:

Your function buscando_dados executes the jQuery POST method that makes an asynchronous request in AJAX you need to proceed with the execution after the POST função callback.

A solution for what you want, this could be it.

function buscando_dados(func){
   $.post('ajax.php',{},function(dados){
      func.call(this,dados);
   });
}
function buscar_dados(){
   buscando_dados(function(dados){
       alert('prosseguindo'); //Prosseguindo está função sem esperar a outra acabar a 
   });

} 

we pass a function by parameter which is executed in the POST function callback ;

Scroll to Top