Home >Web Front-end >JS Tutorial >Detailed explanation of js asynchronous programming method examples

Detailed explanation of js asynchronous programming method examples

小云云
小云云Original
2018-03-08 15:59:551655browse

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

to wait. It 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 a dead

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 task execution mode 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 the tasks;

"Asynchronous mode" is completely different. Each task has one or more callback functions (callback). After the previous task ends, instead of executing the next task,

executes the callback function, and the next task It is executed without waiting for the previous task to end, so the execution order of the program 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, server performance will

drop sharply, very quickly will lose response.

4 methods of "asynchronous mode" programming:

1. Callback function: This is the most basic method of asynchronous programming.

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

function f1(callback){

    setTimeout(function () {

        // f1的任务代码

        callback();

    }, 1000);

}

The execution code becomes as follows: f1(f2);

In this way, we turn the synchronous operation into an asynchronous operation, and f1 will not block the program running, which is equivalent to Execute the main logic of the program first and postpone 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 be specified A callback function.

2. 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 as an example. First, bind an event to f1 (jQuery is used here).

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:

function f1(){

    setTimeout(function () {

        // 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 (Observer Mode)

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

We assume that there is a "signal center". When a task is completed, it "publish" a signal to the signal center. Other tasks can "subscribe" to the signal center. So you know when you can start executing. 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 "Signal Center" jQuery.

jQuery.subscribe("done", f2);

Then, f1 is rewritten as follows:

function f1(){

    setTimeout(function () {

        // 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. This triggers the execution of f2.

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

jQuery.unsubscribe("done", f2);

The nature of this method is similar to "event listening", but it is obviously better than the latter. Because we can monitor the running 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:

f1().then(f2);

f1().then(f2);

f1要进行如下改写(这里使用的是jQuery的实现):

function f1(){

    var dfd = $.Deferred();

    setTimeout(function () {

        // f1的任务代码

        dfd.resolve();

    }, 500);

return dfd.promise;

}

这样写的优点在于,回调函数变成了链式写法,程序的流程可以看得很清楚,而且有一整套的配套方法,可以实现许多强大的功能。

比如,指定多个回调函数:

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

再比如,指定发生错误时的回调函数:

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

而且,它还有一个前面三种方法都没有的好处:如果一个任务已经完成,再添加回调函数,该回调函数会立即执行。所以,你不用担心是否错过了某个事件或信号。这种方法的缺点就是编写和理解,都相对比较难。

相关推荐:

实例详解js异步编程

JS异步编程实例详解

详谈nodejs异步编程_node.js

The above is the detailed content of Detailed explanation of js asynchronous programming method examples. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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