Four Asynchronous Javascript programming methods allow you to write better programs _ javascript skills-js tutorial

Source: Internet
Author: User
This article summarizes four methods of programming in & quot; asynchronous mode & quot, understanding them will allow you to write Javascript programs with a more reasonable structure, better performance, and more convenient maintenance. You may know that the execution environment of the Javascript language is "single thread ).
A single thread means that only one task can be completed at a time. If there are multiple tasks, you must queue up, complete the previous task, and then execute the next task, and so on.

The advantage of this mode is that the implementation is relatively simple, and the execution environment is relatively simple. The disadvantage is that as long as one task takes a long time, the subsequent tasks must be waiting in queue, which will delay the execution of the entire program. Common browsers do not respond (false), because a Javascript code runs for a long time (such as an endless loop), the entire page is stuck in this place, and other tasks cannot be executed.

To solve this problem, the Javascript language divides the task execution mode into two types: Synchronous and Asynchronous).

"Synchronization mode" is the mode of the previous section. The latter task is waiting for the previous task to end and then executed. The execution sequence of the program is consistent with the task arrangement order; the asynchronous mode is completely different. Each task has one or more callback functions. After the previous task is completed, the callback function is executed instead of the last one, the latter task is executed without the end of the previous task. Therefore, the execution sequence of the program is inconsistent and asynchronous with that of the task.

"Asynchronous mode" is very important. On the browser side, all the operations that take a long time should be executed asynchronously to avoid the browser's loss of response. The best example is Ajax operations. On the server side, the "asynchronous mode" is even the only mode, because the execution environment is single-threaded. If you allow synchronous execution of all http requests, the server performance will drop sharply, soon the response will be lost.

This article summarizes four methods of "asynchronous mode" programming. Understanding these methods can help you write Javascript programs with a more reasonable structure, better performance, and more convenient maintenance.

I. Callback Functions
This is the most basic method of asynchronous programming.
Assume that there are two functions f1 and f2, and the latter waits for the execution result of the former.

The Code is as follows:


F1 ();
F2 ();


If f1 is a time-consuming task, you can rewrite f1 and write f2 as the callback function of f1.

The Code is as follows:


Function f1 (callback ){
SetTimeout (function (){
// F1 task code
Callback ();
},1000 );
}


The Execution Code is as follows:

The Code is as follows:


F1 (f2 );


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

The advantages of callback functions are simple, easy to understand, and easy to deploy. The disadvantage is that they are not conducive to code reading and maintenance. The highly coupled interfaces between various parts make the process messy, in addition, only one callback function can be specified for each task.

Ii. event monitoring
Another idea is to adopt the event-driven model. Task execution does not depend on the code sequence, but on whether an event occurs.
Take f1 and f2 as examples. First, bind an event to f1 (jQuery is used here ).

The Code is as follows:


F1.on ('done', f2 );


The code above indicates that f2 is executed when the f1 done event occurs. Then rewrite f1:

The Code is as follows:


Function f1 (){
SetTimeout (function (){
// F1 task code
F1.trigger ('done ');
},1000 );
}


F1.trigger ('done') indicates that after the execution is complete, the done event is triggered immediately to start executing f2.
The advantage of this method is that it is easy to understand and can be bound to multiple events. Each event can specify multiple callback functions and can be "Decoupling", which facilitates modularization. The disadvantage is that the entire program will become event-driven, and the running process will become unclear.
3. Publish/Subscribe
The "Event" in the previous section can be fully understood as "signal ".
We assume that there is a "signal center". When a task is completed, a signal is published to the signal center (publish). Other tasks can subscribe to the signal center) this signal to know when you can start execution. This is called publish-subscribe pattern and observer pattern ).

This mode has multiple implementations. The following uses Tiny Pub/Sub of Ben Alman, which is a plug-in of jQuery.
First, f2 subscribes to the "done" signal from the "signal center" jQuery.

The Code is as follows:


JQuery. subscribe ("done", f2 );


Then, f1 is rewritten as follows:

The Code is as follows:


Function f1 (){
SetTimeout (function (){
// F1 task code
JQuery. publish ("done ");
},1000 );
}


JQuery. publish ("done") means that after f1 is executed, the "done" signal is published to "signal center" jQuery, which triggers f2 execution.
In addition, you can unsubscribe after f2 is executed ).

The Code is as follows:


JQuery. unsubscribe ("done", f2 );


This method is similar to "event listening", but is superior to the latter. Because we can view the message center to know how many signals exist and how many subscribers each signal has, so as to monitor the program running.

4. Promises object
The Promises object is a specification proposed by the CommonJS Working Group to provide a unified interface for asynchronous programming.
Simply put, the idea is that each asynchronous task returns a Promise object with a then method that allows you to specify a callback function. For example, the f1 callback function f2 can be written:

The Code is as follows:


F1 (). then (f2 );


F1 needs to be rewritten as follows (jQuery implementation is used here ):

The Code is as follows:


Function f1 (){
Var dfd = $. Deferred ();
SetTimeout (function (){
// F1 task code
Dfd. resolve ();
},500 );
Return dfd. promise;
}


The advantage of this writing is that the callback function has become a chained writing method, and the process of the program can be clearly viewed. In addition, there is a complete set of supporting methods that can implement many powerful functions.

For example, specify multiple callback functions:

The Code is as follows:


F1 (). then (f2). then (f3 );


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

The Code is as follows:


F1 (). then (f2). fail (f3 );


In addition, it does not benefit from the previous three methods: If a task has been completed and a callback function is added, the callback function will be executed immediately. Therefore, you don't have to worry about missing an event or signal. The disadvantage of this method is that it is relatively difficult to write and understand it.
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.