0

I just read the book "JavaScript: The Good Parts".
And there was an example in the Callback function part

bad way:

   request = prepare_the_request();
    response = send_request_synchronously(request);
    display(response);

recommended way:

request = prepare_the_request();
send_request_asynchronously(request, function(response){
    display(response);
  }):


The problem is i can't understand the difference and the effect taken by the bad way example.
Could anyone explain it in easy way?

WendellLiu
  • 307
  • 5
  • 12
  • Not a direct answer, but there's quite a lot of info in [this question](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call). The problem with the "bad way" is that while waiting for the response, the browser will be frozen. The "recommended way" does it asynchronously, which means that any code directly *after* the code in your example will execute immediately, not waiting for the response. So any code that *relies* on the response needs to be inside the callback. –  Oct 02 '15 at 04:08
  • Oh, the point is "any code directly after the code". I got it! thanks! – WendellLiu Oct 02 '15 at 04:20

2 Answers2

0

Synchronous methods stop your program. Asynchronous methods let it go on, informing you when they are done. This is particularly bad in browsers, for example - if your program blocks, nothing else gets done, including responding to buttons, repainting the screen, animating the swirly GIFS... nothing.

In an analogy, let's look at telling your kid to clean the table before dinner. In an asynchronous scenario, you tell the kid to clean the table, then watch him. A bell rings, guests coming, but you are busy watching your kid clean the table. When he is done, you nod, then go to open the door, and bring out the lunch. The guests are grumpy because you left them waiting outside, and the lunch is cold.

In an asynchronous scenario, you tell the kid to clean the table and tell you when he's done. Bell rings; you answer the door, show the guests in. The kid calls to you ("callback") that he's done with the table cleaning, so you bring out the hot food onto it, and everyone is happy.

Amadan
  • 191,408
  • 23
  • 240
  • 301
0

The main difference is that in the bad way, the synchronously request will BLOCK the UI and the browser might stay unresponsive till the request comes back.

If you send an asynchronously request, the browser will use another thread and the main thread can carry on with the execution of the code, not blocking the UI. The challenge in this approach is that display(response) CANNOT run immediately after the request is sent. it MUST run AFTER the request comes back from the server. That's why we create a CALLBACK function which will be called once the response comes back.

Does it help?

ThiagoPXP
  • 5,362
  • 3
  • 31
  • 44