Home >Web Front-end >JS Tutorial >Detailed explanation of 4 ways to implement asynchronous JavaScript
You may know that the execution environment of the Javascript language is "Single thread
" (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. , 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 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 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, it executes the callback function. The latter task does not wait for the previous one. The tasks are executed when they are finished, 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, 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.
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.
f1(); f2();
If f1 is a time-consuming task, you can consider rewriting f1 and writing f2 as the callback function of f1.
function f1(callback){ setTimeout(function () { // f1的任务代码 callback(); }, 1000); }
The execution code will become as follows:
f1(f2);
In this way, we turn the synchronous operation into an asynchronous operation. F1 will not block the running of the program, which is equivalent to executing the program first. The main logic is to 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
), and the process will be very confusing. Only one callback function can be specified per task.
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).
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, thus starting to execute 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" (Decoupling), which is beneficial to the implementation of modules change. The disadvantage is that the entire program must become event-driven, and the running process will become very unclear.
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 following 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")
的意思是,f1执行完成后,向”信号中心”jQuery发布”done”信号,从而引发f2的执行。
此外,f2完成执行后,也可以取消订阅(unsubscribe)。
jQuery.unsubscribe("done", f2);
这种方法的性质与”事件监听”类似,但是明显优于后者。因为我们可以通过查看”消息中心”,了解存在多少信号、每个信号有多少订阅者,从而监控程序的运行。
Promises
对象是CommonJS
工作组提出的一种规范,目的是为异步编程提供统一接口。
简单说,它的思想是,每一个异步任务返回一个Promise
对象,该对象有一个then方法,允许指定回调函数。比如,f1的回调函数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);
而且,它还有一个前面三种方法都没有的好处:如果一个任务已经完成,再添加回调函数,该回调函数会立即执行。所以,你不用担心是否错过了某个事件或信号。这种方法的缺点就是编写和理解,都相对比较难。
The above is the detailed content of Detailed explanation of 4 ways to implement asynchronous JavaScript. For more information, please follow other related articles on the PHP Chinese website!