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

Introduction to 4 methods of asynchronous programming in Javascript

一个新手
Release: 2017-10-02 12:13:00
Original
1213 people have browsed it

You may know that the execution environment of the 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 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. 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 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.

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.

f1();f2();
Copy after login

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);
  }
Copy after login

The execution code will become as follows:

  f1(f2);
Copy after login

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), the process will be very confusing, and each task can only be specified A 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.
Still take f1 and f2 as an example. First, bind an event to f1 (jQuery is used here).

f1.on('done', f2);
Copy after login

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);
  }
Copy after login

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 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", also known as the "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);
Copy after login

Then, f1 is rewritten as follows:

  function f1(){    
      setTimeout(function () {      // f1的任务代码      
      jQuery.publish("done");
    }, 1000);
  }
Copy after login

jQuery.publish("done") means that after f1 is executed, publish "done" to "Signal Center" jQuery ” signal, thus triggering the execution of f2.

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

 jQuery.unsubscribe("done", f2);
Copy after login

The nature of this method is similar to "event listening", but it is obviously 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:

f1().then(f2);
Copy after login

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

  function f1(){    
      var dfd = $.Deferred();
    setTimeout(function () {      // f1的任务代码      
    dfd.resolve();
    }, 500);
    return dfd.promise;
  }
Copy after login

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

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

f1().then(f2).then(f3);
Copy after login

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

 f1().then(f2).fail(f3);
Copy after login

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

你可能知道,Javascript语言的执行环境是”单线程”(single thread)。

所谓”单线程”,就是指一次只能完成一件任务。如果有多个任务,就必须排队,前面一个任务完成,再执行后面一个任务,以此类推。

这种模式的好处是实现起来比较简单,执行环境相对单纯;坏处是只要有一个任务耗时很长,后面的任务都必须排队等着,会拖延整个程序的执行。常见的浏览器无响应(假死),往往就是因为某一段Javascript代码长时间运行(比如死循环),导致整个页面卡在这个地方,其他任务无法执行。

为了解决这个问题,Javascript语言将任务的执行模式分成两种:同步(Synchronous)和异步(Asynchronous)。

“同步模式”就是上一段的模式,后一个任务等待前一个任务结束,然后再执行,程序的执行顺序与任务的排列顺序是一致的、同步的;”异步模式”则完全不同,每一个任务有一个或多个回调函数(callback),前一个任务结束后,不是执行后一个任务,而是执行回调函数,后一个任务则是不等前一个任务结束就执行,所以程序的执行顺序与任务的排列顺序是不一致的、异步的。

“异步模式”非常重要。在浏览器端,耗时很长的操作都应该异步执行,避免浏览器失去响应,最好的例子就是Ajax操作。在服务器端,”异步模式”甚至是唯一的模式,因为执行环境是单线程的,如果允许同步执行所有http请求,服务器性能会急剧下降,很快就会失去响应。

The above is the detailed content of Introduction to 4 methods of asynchronous programming in Javascript. For more information, please follow other related articles on the PHP Chinese website!

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!