[Effective JavaScript note] 61st: do not block I/O event queues

Source: Internet
Author: User

JS programs are built on top of events. The input may come from a different external source. In some languages, we are accustomed to writing code to wait for a particular input.

var text=downloadSync(‘http://example.com/file.txt‘);console.log(text);

The form downloadsync like this is called a synchronous function (or blocking function). The program will stop doing any work while waiting for its input. In this example, it is the result of waiting for a file to be downloaded from the network. Because the computer can do other useful work while waiting for the download to complete, such a language usually provides a way for programmers to create multiple threads, that is, to perform sub-computations in parallel. It allows a part of the program to stop waiting (to block) a low-speed input, while another part of the program can continue to work independently.
In JS, most I/O operations provide asynchronous or non-blocking APIs. The programmer provides a callback function that can be called by the system once the input is complete, rather than the program blocking the thread waiting for the result.

var text=downloadSync(‘http://example.com/file.txt‘,function(text){  console.log(text);});

The API initializes the download, and then returns immediately after the callback function is stored in the internal registry, rather than being blocked by the network request. When the download is complete, the system invokes the registered callback function as an argument to the text of the downloaded file.
As the event occurs, the event is added to the end of the event queue for the application. The JS system uses an internal loop mechanism to execute the application. The loop mechanism pulls events at the bottom of the queue each time to receive the sequence of these events to invoke these already registered JS event handlers and to use the event's data as parameters for the event handler.
The benefit of running to the completion mechanism guarantee is that you fully master the state of the application while the code is running. There is no need to worry about changes in variables and object properties that are beyond your control because of concurrent execution of code. Concurrent programming is often easier in JS than using threads and locks for C++,java or C #.
However, the inadequacy of the run-to-completion mechanism is that virtually all the code you write supports the continuation of the remaining applications. In an interactive application such as a browser, a blocking event handler blocks any other user input that will be processed and may even block the rendering of a page, causing the page to lose its response to the user experience. In a server environment, a blocking event handler may block other network requests that will be processed, causing the server to lose its response.
One of the most important rules for JS concurrency is never to use the blocking I/O APIs in the application event queue. In the browser, even almost no blocking API is available, although there are some platforms implemented. The XMLHttpRequest Library, which provides network I/O similar to the Downloadasync feature, has a synchronous version implementation that is considered bad. For Web application interactivity, synchronous I/O can have catastrophic consequences that block the user's interaction with the page until the I/O operation is complete.
In contrast, asynchronous APIs are safe in event-based environments, forcing application logic to continue processing in a separate event loop "polling". As in the above example, it is assumed that a few seconds to download the network resources, during this time, a large number of other events are likely to occur. In the implementation of synchronization, these events accumulate in the event queue, and the event loop will stay waiting for the JS code to complete, which will block the processing of any other event. In the asynchronous version, the JS code registers an event handler and returns immediately, which allows other handlers to handle events for the period before the download is complete.
In environments where the main application event queue is not affected, blocking operations rarely have problems. For example, the Web platform provides the worker's API, which makes it possible to generate a large number of parallel computations. Unlike traditional thread execution, workers executes in a completely isolated state without the ability to acquire global scope or the content of the application's main thread Web page. Therefore, they do not interfere with the execution of code running in the main event queue. In a worker, variants that use XMLHttpRequest synchronization are rarely problematic. The download does block the worker from continuing, but this does not prevent the page from rendering or event responses in the event queue. In a server-side environment, the blocking API is not problematic at start-up, that is, before the server starts responding to input requests. Then, during the processing of the request, there is a problem with the blocking API in the browser event queue. Tips

    • Asynchronous APIs use callback functions to slow down processing expensive operations to avoid blocking the main application

    • JS receives the event concurrently, but uses an event queue to process the event handler sequentially

    • Never use blocked I/O in the Application event queue

[Effective JavaScript note] 61st: do not block I/O event queues

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.