简体   繁体   English

回调函数和异步应用

[英]callback function and asynchronous application

I just read the book "JavaScript: The Good Parts". 我刚刚读过“ JavaScript:好的部分”这本书。
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? 谁能以简单的方式解释它?

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. 例如,这在浏览器中尤其糟糕-如果您的程序被阻止,则其他任何事情都无法完成,包括响应按钮,重新绘制屏幕,​​为漩涡状的GIFS设置动画……什么都没有。

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. 您接听门,向客人展示。孩子打电话给您(“回叫”),他已经完成了餐桌清洁工作,因此您将热食带到了餐桌上,每个人都很高兴。

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. 主要区别在于,以糟糕的方式 ,同步请求将阻塞UI,并且浏览器可能会保持无响应,直到请求返回为止。

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. 如果发送异步请求,浏览器将使用另一个线程,并且主线程可以继续执行代码,而不会阻塞UI。 The challenge in this approach is that display(response) CANNOT run immediately after the request is sent. 这种方法的挑战在于,发送请求后,不能立即运行display(response) 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. 这就是为什么我们创建一个CALLBACK函数,一旦响应返回它将被调用。

Does it help? 有帮助吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM