Javascript function does not wait for another to start

Asked

Viewed 4,878 times

9

Problem

My role is not waiting for the other to be finished 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 for the alert('prosseguindo'); be executed only after the alert('dados'); and at the moment this is not happening.

How can I do that?

  • 1

    That’s a great question, why did she get negative? It helped me a lot, I can’t accept it. : S

  • "anxious" is an adjective that cannot be assigned to a computer program, it is the same thing to have questions here with a title "Hopeful function" or "Confident function", it was not I who negatived but I believe I understand the reason.

  • Stop fighting, don’t be anxious.

  • 1

    Why does this question have the tag [tag:php]?

  • @Luizvieira because he makes an ajax request for php

  • Okay, but that’s not the point of the question, okay?

  • 1

    @Luizvieira right, I’ll take..

  • 1

    I think it makes sense to take. I didn’t take because, after all, the question is yours. :)

  • Didn’t really need the php rs tag..

Show 4 more comments

2 answers

12


Its function buscando_dados performs the method POST of jQuery which makes an asynchronous request in AJAX you need to proceed with the execution after the callback of the função POST.

A solution for what you want, can be this.

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 per parameter that is executed in callback of the POST function;

2

You can also use Ajax synchronously.

function buscando_dados(){
   $.ajaxSetup({async: false});
   $.post('ajax.php',{},function(dados){
      alert(dados); 
   });
   $.ajaxSetup({async: true});
}

function buscar_dados(){
   buscando_dados();
   alert('prosseguindo');
} 

Example in Jsfiddle.

Browser other questions tagged

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