Home > Web Front-end > JS Tutorial > body text

4 ways to implement asynchronous programming patterns in JavaScript_javascript skills

WBOY
Release: 2016-05-16 16:35:40
Original
923 people have browsed it

You may know that the execution environment of Javascript language is "single thread".

The so-called "single thread" means that only one task can be completed at a time. If there are multiple tasks, they must be queued. After the previous task is completed, the next task will be executed, and so on.

The advantage of this mode is that it is relatively simple to implement and the execution environment is relatively simple; the disadvantage is that as long as one task takes a long time, subsequent tasks must be queued up, which will delay the execution of the entire program. Common browser unresponsiveness (suspended death) is often caused by a certain piece of Javascript code running for a long time (such as an infinite loop), causing the entire page to get stuck in this place and other tasks cannot be performed.

In order to solve this problem, the Javascript language divides the execution mode of tasks into two types: synchronous (Synchronous) and asynchronous (Asynchronous).

"Synchronous mode" is the mode in the previous paragraph. The latter task waits for the previous task to end before executing it. The execution order of the program is consistent and synchronous with the order of tasks; "asynchronous mode" is completely different. Each task has one or more callback functions (callback). After the previous task ends, the next task is not executed, but the callback function is executed. The latter task is executed without waiting for the previous task to end, so the execution of the program The order is inconsistent and asynchronous with the order of tasks.

"Asynchronous mode" is very important. On the browser side, long-running operations should be performed asynchronously to avoid the browser becoming unresponsive. The best example is Ajax operations. On the server side, "asynchronous mode" is even the only mode, because the execution environment is single-threaded. If all http requests are allowed to be executed synchronously, the server performance will drop sharply and it will soon lose response.

This article summarizes 4 methods of "asynchronous mode" programming. Understanding them will allow you to write Javascript programs with a more reasonable structure, better performance, and easier maintenance.

1. Callback function

This is the most basic method of asynchronous programming.

Suppose there are two functions f1 and f2, and the latter waits for the execution result of the former.

Copy code The code is as follows:

f1();
f2();

If f1 is a time-consuming task, you can consider rewriting f1 and writing f2 as the callback function of f1.

Copy code The code is as follows:

function f1(callback){

setTimeout(function () {

// Task code of f1

callback();

  }, 1000);

 }


The executed code will become as follows:
Copy code The code is as follows:

f1(f2);

Using this method, we turn synchronous operations into asynchronous operations. F1 will not block the running of the program. It is equivalent to executing the main logic of the program first and postponing the execution of time-consuming operations.

The advantage of the callback function is that it is simple, easy to understand and deploy. The disadvantage is that it is not conducive to reading and maintaining the code. The various parts are highly coupled (Coupling), the process will be very confusing, and each task can only specify one callback function. .

2. Event monitoring

Another way of thinking is to use the event-driven model. The execution of a task does not depend on the order of the code, but on whether an event occurs.

Let’s take f1 and f2 as an example. First, bind an event to f1 (jQuery is used here).

Copy code The code is as follows:

f1.on('done', f2);

The above line of code means that when the done event occurs in f1, f2 will be executed. Then, rewrite f1:
Copy code The code is as follows:

function f1(){

setTimeout(function () {

// Task code of f1

  f1.trigger('done');

  }, 1000);

 }


f1.trigger('done') means that after the execution is completed, the done event will be triggered immediately to start executing f2.

The advantage of this method is that it is relatively easy to understand, can bind multiple events, each event can specify multiple callback functions, and can be "decoupled", which is conducive to modularization. The disadvantage is that the entire program must become event-driven, and the running process will become very unclear.

3. Publish/Subscribe

The "event" in the previous section can be understood as a "signal".

We assume that there is a "signal center". When a certain task is executed, it "publish" a signal to the signal center. Other tasks can "subscribe" to the signal from the signal center to know what You can start executing it yourself. This is called the "publish-subscribe pattern" (publish-subscribe pattern), also known as the "observer pattern" (observer pattern).

There are many implementations of this pattern. The one used below is Ben Alman’s Tiny Pub/Sub, which is a plug-in for jQuery.

First, f2 subscribes to the "done" signal from the "Signal Center" jQuery.

Copy code The code is as follows:

jQuery.subscribe("done", f2);

Then, f1 is rewritten as follows:
Copy code The code is as follows:

function f1(){

setTimeout(function () {

// Task code of f1

jQuery.publish("done");

  }, 1000);

 }


jQuery.publish("done") means that after the execution of f1 is completed, the "done" signal is released to the "signal center" jQuery, thereby triggering the execution of f2.

In addition, after f2 completes execution, you can also unsubscribe.

Copy code The code is as follows:

jQuery.unsubscribe("done", f2);

The nature of this method is similar to "event listening", 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 exist and how many subscribers each signal has.

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, which has a then method that allows a callback function to be specified. For example, the callback function f2 of f1 can be written as:

Copy code The code is as follows:

f1().then(f2);

f1 needs to be rewritten as follows (the jQuery implementation is used here):
Copy code The code is as follows:

function f1(){

 var dfd = $.Deferred();

setTimeout(function () {

// Task code of f1

 dfd.resolve();

  }, 500);

Return dfd.promise;

 }


The advantage of writing this way is that the callback function becomes a chain writing method, the program flow can be seen clearly, and there is a complete set of supporting methods that can realize many powerful functions.

For example, specify multiple callback functions:

Copy code The code is as follows:

f1().then(f2).then(f3);

For another example, specify the callback function when an error occurs:
Copy code The code is as follows:

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

Moreover, it has an advantage that the previous three methods do not have: if a task has been completed and a callback function is added, the callback function will be executed immediately. So 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.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!