Home Web Front-end JS Tutorial Introduction to 4 methods of asynchronous programming in Javascript

Introduction to 4 methods of asynchronous programming in Javascript

Oct 02, 2017 pm 12:13 PM
javascript js introduce

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed introduction to what wapi is Detailed introduction to what wapi is Jan 07, 2024 pm 09:14 PM

Users may have seen the term wapi when using the Internet, but for some people they definitely don’t know what wapi is. The following is a detailed introduction to help those who don’t know to understand. What is wapi: Answer: wapi is the infrastructure for wireless LAN authentication and confidentiality. This is like functions such as infrared and Bluetooth, which are generally covered near places such as office buildings. Basically they are owned by a small department, so the scope of this function is only a few kilometers. Related introduction to wapi: 1. Wapi is a transmission protocol in wireless LAN. 2. This technology can avoid the problems of narrow-band communication and enable better communication. 3. Only one code is needed to transmit the signal

Detailed explanation of whether win11 can run PUBG game Detailed explanation of whether win11 can run PUBG game Jan 06, 2024 pm 07:17 PM

Pubg, also known as PlayerUnknown's Battlegrounds, is a very classic shooting battle royale game that has attracted a lot of players since its popularity in 2016. After the recent launch of win11 system, many players want to play it on win11. Let's follow the editor to see if win11 can play pubg. Can win11 play pubg? Answer: Win11 can play pubg. 1. At the beginning of win11, because win11 needed to enable tpm, many players were banned from pubg. 2. However, based on player feedback, Blue Hole has solved this problem, and now you can play pubg normally in win11. 3. If you meet a pub

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Detailed introduction to whether i5 processor can install win11 Detailed introduction to whether i5 processor can install win11 Dec 27, 2023 pm 05:03 PM

i5 is a series of processors owned by Intel. It has various versions of the 11th generation i5, and each generation has different performance. Therefore, whether the i5 processor can install win11 depends on which generation of the processor it is. Let’s follow the editor to learn about it separately. Can i5 processor be installed with win11: Answer: i5 processor can be installed with win11. 1. The eighth-generation and subsequent i51, eighth-generation and subsequent i5 processors can meet Microsoft’s minimum configuration requirements. 2. Therefore, we only need to enter the Microsoft website and download a "Win11 Installation Assistant" 3. After the download is completed, run the installation assistant and follow the prompts to install Win11. 2. i51 before the eighth generation and after the eighth generation

Introducing the latest Win 11 sound tuning method Introducing the latest Win 11 sound tuning method Jan 08, 2024 pm 06:41 PM

After updating to the latest win11, many users find that the sound of their system has changed slightly, but they don’t know how to adjust it. So today, this site brings you an introduction to the latest win11 sound adjustment method for your computer. It is not difficult to operate. And the choices are diverse, come and download and try them out. How to adjust the sound of the latest computer system Windows 11 1. First, right-click the sound icon in the lower right corner of the desktop and select "Playback Settings". 2. Then enter settings and click "Speaker" in the playback bar. 3. Then click "Properties" on the lower right. 4. Click the "Enhance" option bar in the properties. 5. At this time, if the √ in front of "Disable all sound effects" is checked, cancel it. 6. After that, you can select the sound effects below to set and click

PyCharm Beginner's Guide: Comprehensive Analysis of Replacement Functions PyCharm Beginner's Guide: Comprehensive Analysis of Replacement Functions Feb 25, 2024 am 11:15 AM

PyCharm is a powerful Python integrated development environment with rich functions and tools that can greatly improve development efficiency. Among them, the replacement function is one of the functions frequently used in the development process, which can help developers quickly modify the code and improve the code quality. This article will introduce PyCharm's replacement function in detail, combined with specific code examples, to help novices better master and use this function. Introduction to the replacement function PyCharm's replacement function can help developers quickly replace specified text in the code

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

What is Dogecoin What is Dogecoin Apr 01, 2024 pm 04:46 PM

Dogecoin is a cryptocurrency created based on Internet memes, with no fixed supply cap, fast transaction times, low transaction fees, and a large meme community. Uses include small transactions, tips, and charitable donations. However, its unlimited supply, market volatility, and status as a joke coin also bring risks and concerns. What is Dogecoin? Dogecoin is a cryptocurrency created based on internet memes and jokes. Origin and History: Dogecoin was created in December 2013 by two software engineers, Billy Markus and Jackson Palmer. Inspired by the then-popular "Doge" meme, a comical photo featuring a Shiba Inu with broken English. Features and Benefits: Unlimited Supply: Unlike other cryptocurrencies such as Bitcoin

See all articles