Home Web Front-end JS Tutorial Detailed explanation of JavaScript function asynchronous execution implementation code

Detailed explanation of JavaScript function asynchronous execution implementation code

Jul 22, 2017 am 10:56 AM
javascript js accomplish

Suppose you have several functions fn1, fn2 and fn3 that need to be called in sequence. The simplest way is of course:


fn1();
fn2();
fn3();
Copy after login

But there are At this time, these functions are added one by one during runtime, and you don't know what functions there are when you call them; at this time, you can pre-define an array, push the functions into it when adding functions, and select them one by one from the array in order when needed. Take it out and call it in sequence:


var stack = [];
// 执行其他操作,定义fn1
stack.push(fn1);
// 执行其他操作,定义fn2、fn3
stack.push(fn2, fn3);
// 调用的时候
stack.forEach(function(fn) { fn() });
Copy after login

It doesn’t matter whether the function has a name or not, you can just pass the anonymous function in directly. Let’s test it:


var stack = [];
function fn1() {
  console.log('第一个调用');
}
stack.push(fn1);

function fn2() {
  console.log('第二个调用');
}
stack.push(fn2, function() { console.log('第三个调用') });

stack.forEach(function(fn) { fn() }); // 按顺序输出'第一个调用'、'第二个调用'、'第三个调用'
Copy after login

This implementation works fine so far, but we ignored one situation, which is the call of asynchronous functions. Asynchrony is an unavoidable topic in JavaScript. I am not going to discuss the various terms and concepts related to asynchronous in JavaScript here. Readers are asked to check it out by themselves (such as a famous commentary). If you know that the following code will output 1, 3, and 2, then please continue reading:


console.log(1);

setTimeout(function() {
  console.log(2);
}, 0);

console.log(3);
Copy after login

If there is a function in the stack queue that is similar As for the asynchronous function, our implementation is messed up:


var stack = [];

function fn1() { console.log('第一个调用') };
stack.push(fn1);

function fn2() {
  setTimeout(function fn2Timeout() {
     console.log('第二个调用');
  }, 0);
}
stack.push(fn2, function() { console.log('第三个调用') });

stack.forEach(function(fn) { fn() }); // 输出'第一个调用'、'第三个调用'、'第二个调用'
Copy after login

The problem is obvious, fn2 is indeed called in sequence, but the function fn2Timeout() { console in setTimeout .log('Second call') } is not executed immediately (even if timeout is set to 0); fn2 returns immediately after the call, and then executes fn3. After fn3 is executed, it is really fn2Timeout's turn.

How to deal with it? Let's analyze it. The key here is fn2Timeout. We must wait until it is actually executed before calling fn3. Ideally it would be like this:


function fn2() {
  setTimeout(function() {
    fn2Timeout();
    fn3();
  }, 0);
}
Copy after login

But do this It is equivalent to removing the original fn2Timeout and replacing it with a new function, and then inserting the original fn2Timeout and fn3. This method of dynamically changing the original function has a special term called Monkey Patch. According to the mantra of our programmers: "It can definitely be done", but it is a bit awkward to write, and it is easy to get yourself involved. Is there a better way?
We take a step back and do not insist on waiting for fn2Timeout to be completely executed before executing fn3. Instead, we call it on the last line of the fn2Timeout function body:


function fn2() {
  setTimeout(function fn2Timeout() {
    console.log('第二个调用');
    fn3();    // 注{1}
  }, 0);
}
Copy after login

This looks better, but when fn2 was defined, there was no fn3 yet. Where did fn3 come from?

There is another problem. Since fn3 needs to be called in fn2, we cannot call fn3 through stack.forEach, otherwise fn3 will be called twice.

We cannot hardcode fn3 into fn2. On the contrary, we only need to find the next function of fn2 in the stack at the end of fn2Timeout, and then call:


function fn2() {
  setTimeout(function fn2Timeout() {
    console.log('第二个调用');
    next();
  }, 0);
}
Copy after login

This next function is responsible for finding the next function in the stack Next function and execute it. Let’s implement next now:


var index = 0;

function next() {
  var fn = stack[index];
  index = index + 1; // 其实也可以用shift 把fn 拿出来
  if (typeof fn === 'function') fn();
}
Copy after login

next uses stack[index] to get the function in the stack. Every time next is called, the index will be increased by 1, thus achieving removal. The purpose of the next function.
Next is used like this:


var stack = [];

// 定义index 和next

function fn1() {
  console.log('第一个调用');
  next(); // stack 中每一个函数都必须调用`next`
};
stack.push(fn1);

function fn2() {
  setTimeout(function fn2Timeout() {
     console.log('第二个调用');
     next(); // 调用`next`
  }, 0);
}
stack.push(fn2, function() {
  console.log('第三个调用');
  next(); // 最后一个可以不调用,调用也没用。
});

next(); // 调用next,最终按顺序输出'第一个调用'、'第二个调用'、'第三个调用'。
Copy after login

Now that the stack.forEach line has been deleted, we call next by ourselves, and next will find the first line in the stack. A function fn1 is executed, next is called in fn1 to find the next function fn2 and executed, then next is called in fn2, and so on.
Every function must call next. If it is not written in a certain function, the program will end directly after executing the function without any mechanism to continue.

After understanding this implementation of function queue, you should be able to solve the following interview question:


// 实现一个LazyMan,可以按照以下方式调用:
LazyMan(“Hank”)
/* 输出: 
Hi! This is Hank!
*/

LazyMan(“Hank”).sleep(10).eat(“dinner”)输出
/* 输出: 
Hi! This is Hank!
// 等待10秒..
Wake up after 10
Eat dinner~
*/

LazyMan(“Hank”).eat(“dinner”).eat(“supper”)
/* 输出: 
Hi This is Hank!
Eat dinner~
Eat supper~
*/

LazyMan(“Hank”).sleepFirst(5).eat(“supper”)
/* 等待5秒,输出
Wake up after 5
Hi This is Hank!
Eat supper
*/

// 以此类推。
Copy after login

Node.js is famous in China This is how the connect framework implements middleware queues.

If you are careful, you may see that this next can only be placed at the end of the function for the time being. If it is placed in the middle, the original problem will still appear:


function fn() {
  console.log(1);
  next();
  console.log(2); // next()如果调用了异步函数,console.log(2)就会先执行
}
Copy after login

Through different implementations, redux and koa can place next in the middle of the function. After executing the subsequent functions, it can then be turned back to execute the code below next, which is very clever. Write again when you have time.

The above is the detailed content of Detailed explanation of JavaScript function asynchronous execution implementation code. 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)

How to implement dual WeChat login on Huawei mobile phones? How to implement dual WeChat login on Huawei mobile phones? Mar 24, 2024 am 11:27 AM

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

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

PHP Programming Guide: Methods to Implement Fibonacci Sequence PHP Programming Guide: Methods to Implement Fibonacci Sequence Mar 20, 2024 pm 04:54 PM

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

How to implement the WeChat clone function on Huawei mobile phones How to implement the WeChat clone function on Huawei mobile phones Mar 24, 2024 pm 06:03 PM

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

How to implement exact division operation in Golang How to implement exact division operation in Golang Feb 20, 2024 pm 10:51 PM

Implementing exact division operations in Golang is a common need, especially in scenarios involving financial calculations or other scenarios that require high-precision calculations. Golang's built-in division operator "/" is calculated for floating point numbers, and sometimes there is a problem of precision loss. In order to solve this problem, we can use third-party libraries or custom functions to implement exact division operations. A common approach is to use the Rat type from the math/big package, which provides a representation of fractions and can be used to implement exact division operations.

Master how Golang enables game development possibilities Master how Golang enables game development possibilities Mar 16, 2024 pm 12:57 PM

In today's software development field, Golang (Go language), as an efficient, concise and highly concurrency programming language, is increasingly favored by developers. Its rich standard library and efficient concurrency features make it a high-profile choice in the field of game development. This article will explore how to use Golang for game development and demonstrate its powerful possibilities through specific code examples. 1. Golang’s advantages in game development. As a statically typed language, Golang is used in building large-scale game systems.

PHP Game Requirements Implementation Guide PHP Game Requirements Implementation Guide Mar 11, 2024 am 08:45 AM

PHP Game Requirements Implementation Guide With the popularity and development of the Internet, the web game market is becoming more and more popular. Many developers hope to use the PHP language to develop their own web games, and implementing game requirements is a key step. This article will introduce how to use PHP language to implement common game requirements and provide specific code examples. 1. Create game characters In web games, game characters are a very important element. We need to define the attributes of the game character, such as name, level, experience value, etc., and provide methods to operate these

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

See all articles