JavaScript Tutorial: Four ways to do asynchronous mode programming

Source: Internet
Author: User
Tags object bind end execution functions thread advantage

Article Introduction: 4 ways of JavaScript asynchronous programming.

As you may know, the execution environment for a JavaScript language is "single-threaded" (single thread).

The so-called "single thread" means that only one task can be completed at a time. If you have more than one task, you must queue, the previous task completes, then the next task, and so on.

The advantage of this model is that it is simpler to implement and a relatively simple execution environment; The downside is that as long as one task takes a long time, the tasks that follow must be queued up, delaying the execution of the entire program. The common browser is unresponsive (suspended animation), often because a section of JavaScript code runs for a long time (such as a dead loop), causing the entire page to be stuck in this place, and other tasks cannot be performed.

To solve this problem, the JavaScript language divides the execution pattern of a task into two types: synchronization (synchronous) and asynchronous (asynchronous).

"Sync Mode" is the pattern of the previous paragraph, the latter task waits for the previous task to finish, then executes, the sequence of execution of the program is consistent with the order of the task, synchronized; "Asynchronous mode" is completely different, each task has one or more callback functions (callback), the previous task is finished, Instead of performing the latter task, the callback function is executed, and the latter task is executed at the end of the previous task, so that the sequence of execution of the program is inconsistent and asynchronous with the order in which the task is ordered.

"Asynchronous mode" is very important. At the browser end, a lengthy operation should be performed asynchronously to avoid the browser losing its response, the best example being Ajax. On the server side, "asynchronous mode" is even the only pattern, because the execution environment is single-threaded, and if all HTTP requests are allowed to execute synchronously, server performance can plummet and quickly lose its response.

This article summarizes the 4 methods of "Asynchronous mode" programming, and understands that they allow you to write JavaScript programs that are more structured, better performing, and easier to maintain.

One, callback function

This is the most basic method of asynchronous programming.

It is assumed that there are two functions F1 and F2, which wait for the results of the former's execution.

F1 ();

F2 ();

If F1 is a time-consuming task, consider rewriting F1 to write F2 as a F1 callback function.

Function F1 (callback) {

settimeout (function () {

F1 's Task code

Callback ();

}, 1000);

}

The execution code becomes the following:

F1 (F2);

In this way, we turn the synchronization operation into an asynchronous operation, and F1 does not jam the program running, which is equivalent to executing the main logic of the program first, delaying the execution of the time-consuming operation.

The advantage of the callback function is simplicity, ease of understanding and deployment, which is not conducive to code reading and maintenance, is highly coupled between parts (coupling), the process is messy, and each task can only specify one callback function.

Second, event monitoring

Another idea is to use event-driven mode. The execution of a task does not depend on the order of the Code, but on whether an event occurs.

Take F1 and F2 for example. First, bind an event to the F1 (the jquery notation used here).

F1.on (' Done ', F2);

The above line of code means that when the F1 occurs, the F2 is executed. Then, rewrite the F1:

Function F1 () {

settimeout (function () {

F1 's Task code

F1.trigger (' done ');

}, 1000);

}

F1.trigger (' Done ') indicates that after the execution is complete, the completed event is triggered immediately to begin execution of the F2.

The advantage of this approach is that it is relatively easy to understand, can bind multiple events, each event can specify multiple callback functions, and can be "decoupled" (decoupling), facilitate the implementation of modularity. The disadvantage is that the entire program becomes an event-driven type, and the running process becomes very unclear.

Third, publish/Subscribe

The "events" in the previous section can be fully understood as "signals."

We assume that there is a "signal center" in which a task is executed to "release" a signal to the signal center, and other tasks can "subscribe" to the Signal Center (subscribe) to know when they can begin to perform publish. This is called "Publish/Subscribe Mode" (Publish-subscribe pattern), also known as "Observer Mode" (Observer patterns).

This pattern is implemented in a variety of ways, using the tiny pub/sub of Ben Alman, which is a plug-in to jquery.

First, F2 subscribe to "done" signals to the "Signal Center" jquery.

Jquery.subscribe ("Done", F2);

The F1 is then rewritten as follows:

Function F1 () {

settimeout (function () {

F1 's Task code

Jquery.publish ("Done");

}, 1000);

}

Jquery.publish ("done") means that after the execution of the F1, the "Do" signal is released to the "Signal Center" jquery, triggering F2 execution.

In addition, you can unsubscribe (unsubscribe) after F2 completes execution.

Jquery.unsubscribe ("Done", F2);

The nature of this approach is similar to "event monitoring", but it is significantly better than the latter. Because we can monitor the operation of the program by looking at the message center to see how many signals there are and how many subscribers each signal has.

Iv. promises objects

The promises object is a specification proposed by the COMMONJS workgroup to provide a unified interface for asynchronous programming.

Simply put, it's thought that each asynchronous task returns a Promise object that has a then method that allows you to specify a callback function. For example, F1 's callback function, F2, can be written as:

F1 (). then (F2);

The F1 is rewritten as follows (the implementation of jquery is used here):

Function F1 () {

var DFD = $. Deferred ();

settimeout (function () {

F1 's Task code

Dfd.resolve ();

}, 500);

return dfd.promise;

}

The advantage of this is that the callback function has become a chain of writing, the process of the program can be seen very clearly, and a complete set of matching methods, can achieve many powerful functions.

For example, specify multiple callback functions:

F1 (). Then (F2). then (F3);

For example, specify the callback function when an error occurs:

F1 (). Then (F2). Fail (F3);

Moreover, it has a benefit that none of the previous three methods do: If a task is completed, and then a callback function is added, the callback function is executed immediately. So you don't have to worry about missing an event or signal. The disadvantage of this method is that it is comparatively difficult to write and understand.

Five, reference links

* Asynchronous Js:callbacks, Listeners, control flow Libs and promises



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.