14
I have an operation that I need to perform synchronously, but part of the information I need can only be obtained via Ajax.
I tried to synchronise everything with a wait for Ajax to return. The problem is that as long as any function is running, Ajax events that handle return successfully do not run.
That’s an example of what I’m doing:
function foo () {
var a = false;
$.ajax({
url: "foo" // substitua por qualquer URL real
}).done(function () {
a = true;
});
while(!a) { } // Isto é apenas para se ter uma espera.
alert(a); // Isso nunca vai executar
}
foo();
And it has generated me race condition
: the function associated with the event done
shall not execute as long as the while
is iterating, and the while
will never end while the event done
not executed.
Is there any way to achieve my goal?
It depends a little on what you want to do, but can always call a closed function out of
.done()
passing the ajax answer as parameter. You can add more code to better understand your problem?– Sergio
Have you ever tried to raise an exception if there is no response from the server? while inside you test if the waiting time is greater than 5 * 60 * 1000 (5 minutes) if true then triggers an exception warning that there was no server response...
– Filipe
@Sergio the problem is simple... Just wait, within a synchronous function, for the return of an asynchronous call. I want to force an operation to be synchronous. I put a little more code just to illustrate better.
– Oralista de Sistemas
@Renan joined a jsFiddle to my comment above. Option is to use
async: false
as the bfavaretto suggested, taking into account the warnings and problems that this can bring.– Sergio
@Renan What prevents you from calling a function with the desired behavior within the done?
– Filipe
@Luizfilipe Nada, just want to perform an entire sequence in a single method. But I’m evaluating the best way to do it yet. Anyway, the bfavaretto’s response was on the fly.
– Oralista de Sistemas
Have you tried a standby solution with setInterval? http://jsfiddle.net/YnbL4/
– Filipe
@Luizfilipe I will try something like this, or transfer the logic to
done
.– Oralista de Sistemas