Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronous/Synchronous Javascript

I'm having some trouble understanding the difference between asynchronous and synchronous Javascript, and was hoping someone could shed some light on this.

I know Javascript is inherently synchronous, but you can use asynchronous events/callbacks to alter your program flow. However, what happens if you call a function with no callback that contains AJAX?

For example, if I have the following code, where foo() contains some sort of server query and foobar() contains some output text:

foo();
foobar();

Will foobar() be called before the internal logic in foo() is complete, or will the browser wait until foo() is fully executed before calling foobar()? (This seems simple, but my confusion arises from callbacks and whether or not they are absolutely necessary in all cases to control your program flow, i.e. if foo(foobar) is always necessary.)

Also, if foo() contains a server call that is quickly executed on the client side but takes a long time on the server to process, is a callback the only way I can make my program wait until foo() is completely done executing?

like image 232
sichinumi Avatar asked Feb 24 '23 13:02

sichinumi


2 Answers

foobar() will indeed be called before the Ajax call in foo() is complete...

Unless, and this is the answer to your second question, you specify that the Ajax call should be synchronous, which is an option. Doing so will force the user to wait until the call completes before they can do anything, so that's usually not the best choice. Using a callback is usually the best approach.

like image 153
Jacob Mattison Avatar answered Mar 07 '23 05:03

Jacob Mattison


Will foobar() be called before the internal logic in foo() is complete

The answer to this question depends on what you mean by "internal logic". foobar will only be called once all of the javascript in foo is complete. It will not however wait for the AJAX call to return (kind of the whole point of the A in AJAX).

like image 25
James Montagne Avatar answered Mar 07 '23 03:03

James Montagne