Skip to content Skip to sidebar Skip to footer

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 inh

Solution 1:

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.

Solution 2:

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).

Solution 3:

All of foo will run, then all of foobar will run.

Part of foo might say "Send an HTTP request asynchronously", in which case it won't wait for the response to come back before continuing (but since foo only triggers the sending of the request, it is considered complete).

If there was a callback, then that would run when the response arrived (which would usually be after foobar was complete).

Solution 4:

In simple terms, foo() will entirely execute internally before foobar() starts. However, if within foo() there is a call to execute an ajax request, that request will be submitted, and will then execute in parallel.

Once the request is submitted the processing will continue. The ajax request will return with a response when it is complete, that may or may not be picked up by further processing.

Solution 5:

Imagine, for example, you have something like this:

var something;
foo(); //Inside foo, the value of something is set to the result of an AJAX call
console.log(something);

The console.log line will print undefined, because the variable something will still be empty, until the AJAX response in foo changes it. This is the sort of situation in which a callback is useful - in the callback you can assign the value of the response to something, and you then know that something has a value.

Your example is very similar to this - foobar will be called as soon as foo returns, and if foo contains some asynchronous logic, it will return before that completes. If you want foobar to execute after, you will need to call it from (or use it as) the callback function.

It would be possible to make foo wait until whatever it does has finished, but that would probably defeat the point of using AJAX, as you'd have to send a synchronous request.

Post a Comment for "Asynchronous/synchronous Javascript"