Tuesday, February 12, 2013

main Difference between Synchronous & Asynchronous

With synchronous calls/postback, you are issuing the command and waiting for the result. So you will not be able to do anything until your request has finished.
With asynchronous calls/postback, you wire your call to "OnFinish" event (this is just a generic event name for the purpose of explanation only) to a delegate and you carry on doing other tasks, when the call finishes this event will fire then you can handle it in your delegate. For example you call a web service, while waiting for the result you can create your database connection, when the result comes back from the call you can insert them in your database.

Sync Request - One way of communication from your application to Data layer (example: validating the login name and password and returning to the user in another page or google search)
Async request - As and when you type the required text, the application estaliblishes connection to the DB and returns answers to the users (example, google suggest) AJAX is a Async

This is a very common question that been asked in all most every basic interview – What is the main strength of AJAX? Or why and when should we use AJAX in web application?
And the most common answer is – “AJAX does not refresh or reload the whole page”.
But, the more perfect answer is – “AJAX is an asynchronous technology where others request are synchronous.”
So, what is the difference?
In a word, a program does not wait for response after requesting an asynchronous call whereas synchronous does so.
Here is a simple example –
function do() {
var a=0;
a = getStatus(“get.php?id=6”);
if(a==1) {
alert(“call response”);
} else {
alert(“notcall response ”);
Here getStatus() function sends a AJAX request to the server with “getstatus.php?id=6” url and the php file decides (from database may be) the status and output/response as 1 or 0.
But, this function will not work properly. It will alert “not active” instead of “active”. And yes, that is for the asynchronous request.
The reason is – when a = getStatus(“getstatus.php?id=5”); line is being executed program does not wait for the response of setStatus() function. So, value of keep unchanged or set to null.
So, how should we work with asynchronous request?
Of course, using callback function. Callback function is that function which is triggered when the request completes to get the response (or as defined).

No comments:

Post a Comment