Is there a way to perform a synchronous AJAX query that doesn't freeze the browser? In my opinion synchronous requests are a lot easier to work with in most cases, but the fact that they block other parts of the code from executing is a real killer. Is there a way to get synchronous AJAX without the negative side effects? (And yes, I realize that the term "Synchronous AJAX" is an oxymoron.)
I'll provide an example of the bad side of effects of allowing such behavior.
Lets say you have this program:
<script>
var file = "foo.json";
function nullIt() {
file = null;
}
function loadFile() {
if (file != null) {
synchronousLoad(file);//imagine the load takes 5 seconds
alert("i just loaded: " + file);
}
}
window.onload = loadFile;
</script>
<button onclick="nullIt()">click me</button>
The bad thing here-
synchronousLoad()
is blocking for 5 seconds, the user clicks the button, and the event handler quickly runs to completion. file
variable is null. synchronousLoad()
finishes and returns, letting execution resume on the next line of codefile
is now null, and the message output to the user is broken.The real issue here you cannot reason about your code the same way anymore. Just because some fact was true on line 5, doesnt mean its still true on the very next line. This makes it very difficult to write an error free program.
Some programming languages support multithreading, and you have to deal with these issues, although you have tools to help deal with these problems. But, it's still a lot of extra effort on the programmers part.
Comparatively speaking, using callbacks to do asynchronous operations is ez-mode.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With