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

Detailed explanation of js asynchronous programming with examples

Mar 07, 2018 am 10:48 AM
javascript asynchronous programming

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. 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 be 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, the 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);

}
Copy after login

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);
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 has to 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 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 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);
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);

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

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

相关推荐:

JS异步编程实例详解

详谈nodejs异步编程_node.js

剖析Node.js异步编程中的回调与代码设计模式_node.js

The above is the detailed content of Detailed explanation of js asynchronous programming with examples. 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)

Remove duplicate values ​​from PHP array using regular expressions Remove duplicate values ​​from PHP array using regular expressions Apr 26, 2024 pm 04:33 PM

How to remove duplicate values ​​from PHP array using regular expressions: Use regular expression /(.*)(.+)/i to match and replace duplicates. Iterate through the array elements and check for matches using preg_match. If it matches, skip the value; otherwise, add it to a new array with no duplicate values.

What is programming for and what is the use of learning it? What is programming for and what is the use of learning it? Apr 28, 2024 pm 01:34 PM

1. Programming can be used to develop various software and applications, including websites, mobile applications, games, and data analysis tools. Its application fields are very wide, covering almost all industries, including scientific research, health care, finance, education, entertainment, etc. 2. Learning programming can help us improve our problem-solving skills and logical thinking skills. During programming, we need to analyze and understand problems, find solutions, and translate them into code. This way of thinking can cultivate our analytical and abstract abilities and improve our ability to solve practical problems.

Asynchronous and non-blocking technology in Java exception handling Asynchronous and non-blocking technology in Java exception handling May 01, 2024 pm 05:42 PM

Asynchronous and non-blocking techniques can be used to complement traditional exception handling, allowing the creation of more responsive and efficient Java applications: Asynchronous exception handling: Handling exceptions in another thread or process, allowing the main thread to continue executing, avoiding blocking. Non-blocking exception handling: involves event-driven exception handling when an I/O operation goes wrong, avoiding blocking threads and allowing the event loop to handle exceptions.

Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Oct 11, 2024 pm 08:58 PM

Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid

Collection of C++ programming puzzles: stimulate thinking and improve programming skills Collection of C++ programming puzzles: stimulate thinking and improve programming skills Jun 01, 2024 pm 10:26 PM

C++ programming puzzles cover algorithm and data structure concepts such as Fibonacci sequence, factorial, Hamming distance, maximum and minimum values ​​of arrays, etc. By solving these puzzles, you can consolidate C++ knowledge and improve algorithm understanding and programming skills.

Unleash Your Inner Programmer: C for Absolute Beginners Unleash Your Inner Programmer: C for Absolute Beginners Oct 11, 2024 pm 03:50 PM

C is an ideal language for beginners to learn programming, and its advantages include efficiency, versatility, and portability. Learning C language requires: Installing a C compiler (such as MinGW or Cygwin) Understanding variables, data types, conditional statements and loop statements Writing the first program containing the main function and printf() function Practicing through practical cases (such as calculating averages) C language knowledge

The Key to Coding: Unlocking the Power of Python for Beginners The Key to Coding: Unlocking the Power of Python for Beginners Oct 11, 2024 pm 12:17 PM

Python is an ideal programming introduction language for beginners through its ease of learning and powerful features. Its basics include: Variables: used to store data (numbers, strings, lists, etc.). Data type: Defines the type of data in the variable (integer, floating point, etc.). Operators: used for mathematical operations and comparisons. Control flow: Control the flow of code execution (conditional statements, loops).

Use golang's error wrapping and unwinding mechanism for error handling Use golang's error wrapping and unwinding mechanism for error handling Apr 25, 2024 am 08:15 AM

Error handling in Go includes wrapping errors and unwrapping errors. Wrapping errors allows one error type to be wrapped with another, providing a richer context for the error. Expand errors and traverse the nested error chain to find the lowest-level error for easy debugging. By combining these two technologies, error conditions can be effectively handled, providing richer error context and better debugging capabilities.

See all articles