


Introduction to the principles and implementation techniques of asynchronous javascript_javascript techniques
Due to work needs, I need to write a script on the web page to submit data to the system in batches through the web page. So I thought of the Greasemonkey plug-in, so I started writing it and found that the problem was solved smoothly. But when summarizing and organizing the script, I habitually asked myself a question: Can it be simpler?
My answer is of course “yes”.
First review my requirements for batch submission of data: I have a batch of user data to be inserted into the system, but because the system library table structure is not determinant, it cannot be converted into SQL statements for insertion. There are nearly 200 pieces of data to be inserted. Even if it is entered into the system manually, it will probably take a day. As a programmer, of course I would not do such a stupid thing, I must use a program to solve it. This programming process took me 1 day. Compared with manual entry, my extra income is from this blog post, which is absolutely cost-effective!
It didn’t take any time to choose the programming platform. I directly chose to write my own script based on Greasemonkey. The browser was of course Firefox. The working process of the script:
Pre-store the data to be inserted in the script
Simulate a mouse click to open the input window on the page
Enter the data into the input window, and simulate clicking the "Submit" button to submit the data submitted to the system.
Loop in sequence until all data is processed.
The technical difficulty here is:
To open the input window, you need to wait for an irregular period of time, depending on the network conditions.
Submit data to the background, and you need to wait for the processing to be completed before you can cycle to the next data.
If I were a novice, of course I would directly write an application logic similar to this:
for(var i = 0; i < dataArray.length; i)
{ 3: clickButtonForInputWindow();
waitInputWindow();
enterInputData(dataArray[i] );
clickSubmitButton();
waitInputWindowClose();
}
In fact, all browsers will fall into a white screen after a few minutes and prompt "No response" and was forcibly terminated. The reason is that when the browser calls JavaScript, the main interface stops responding because the CPU is handed over to js for execution and there is no time to process interface messages.
In order to meet the requirement of "no locking", we can modify the script as follows:
for(var i = 0; i < dataArray.length; i)
{
setTimeout(clickButtonForInputWindow);
…
setTimeout(waitInputWindowClose );
}
In fact, setTimeout and setInterval are the only asynchronous operations that browsers can support. How to use these two functions more elegantly to implement asynchronous operations? The current simple answer is Lao Zhao's Wind.js. Although I have not used this function library, the $await call alone meets my consistent requirement for simplicity. But for a single file script like mine, downloading an external js library from the Internet is obviously not as fast and enjoyable as copying a piece of code that supports asynchronous operations.
So I decided to find another way and make an asynchronous function library that does not require compilation and is easier to use and can be copied and pasted.
Before talking about asynchronous, let’s recall the several structural types of synchronous operations:
Sequence: It is the order in which statements are executed
Judgment: It is the judgment statement
Loop: strict It should be jump (goto), but most modern languages have canceled goto. A loop should actually be a composite structure, a combination of if and goto.
The difficulty of asynchronous operations lies in two places:
Asynchronous judgment: The judgment in asynchronous situations is basically to detect that the conditions are satisfied, and then perform certain actions.
Asynchronous sequence: After each step in the sequence, control is returned and the next step is waited for in the next time slice. The difficulty is maintaining order. Especially when there is an asynchronous loop between two sequential actions.
Asynchronous loop: After each loop, control is returned to the browser, and this loop continues until the end of the run.
The simplest implementation is of course an asynchronous loop. My implementation code is as follows:
function asyncWhile(fn, interval)
{
if( fn == null || (typeof(fn) != "string" && typeof(fn) != "function") )
return;
var wrapper = function()
{
if( (typeof(fn) == "function" ? fn() : eval(fn) ) !== false )
setTimeout(wrapper, interval == null? 1: interval);
}
wrapper();
}
The core content is: if the return value of the fn function is not false, continue with the next setTimeout registration call.
In fact, the "wait and execute" logic is basically an asynchronous loop problem. An example of how to implement this situation is as follows:
asyncWhile(function (){
if( xxxCondition == false )
return true; // Indicates that the loop continues
else
doSomeThing();
return false; // Indicates that there is no need to continue the loop
});
For non-waiting and execution logic, a simple setTimeout is enough.
Asynchronous is easy, but the difficulty is to implement the order in asynchronous. The earliest reason was that I wanted to implement 3 steps, but the second part was an asynchronous loop of more than 100 times. In other words, the 3-step operation I want to implement is actually 103 sequential asynchronous operations. In order to find a way to implement responsive waiting in the browser, I searched my brain and only found an implementation in Firefox, and I had to apply for privileged calls.
Finally, I came up with a simple method, which is to introduce the concept of "Execution Chain". All registration functions of the same execution chain are sequential, and there is no relationship between different execution chains. In addition, it does not provide concepts such as mutual exclusion (mutex). If you want to synchronize, check it yourself in the code.
In the same execution chain, an execution token is saved. Only when the token matches the function serial number can execution be allowed, thus ensuring the order of asynchronous execution.
function asyncSeq(funcArray, chainName, abortWhenError)
{
if( typeof(funcArray) == "function" )
return asyncSeq([funcArray], chainName, abortWhenError);
if( funcArray == null || funcArray.length == 0 )
return;
if( chainName == null ) chainName = "__default_seq_chain__";
var tInfos = asyncSeq.chainInfos = asyncSeq.chainInfos || {};
var tInfo = tInfos[chainName] = tInfos[chainName] || {count : 0, currentIndex : -1, abort : false};
for(var i = 0; i < funcArray.length; i)
{
asyncWhile(function(item, tIndex){
return function(){
if( tInfo.abort )
return false;
if( tInfo.currentIndex < tIndex )
return true;
else if( tInfo.currentIndex == tIndex )
{
try{
item();
}
catch(e){
if ( abortWhenError ) tInfo.abort = true;
}
finally{
tInfo.currentIndex ;
}
}
else
{
if( abortWhenError ) tInfo. abort = true;
}
return false;
};
}(funcArray[i], tInfo.count ));
}
setTimeout(function() {
if( tInfo.count > 0 && tInfo.currentIndex == -1 )
tInfo.currentIndex = 0;
},20); // For debugging reasons, a delayed start is added
}
Thus, an asynchronous js function library supporting Copy&Paste is completed. Specific usage examples are as follows:
function testAsync()
{
asyncSeq([function(){println("aSyncSeq -0 ");}
, function(){println("aSyncSeq -1 ");}
, function(){println("aSyncSeq -2 ");}
, function(){println("aSyncSeq -3 ");}
, function(){println("aSyncSeq -4 ");}
, function(){println("aSyncSeq -5 ");}
, function(){println("aSyncSeq -6 ");}
, function(){println("aSyncSeq -7 ");}
, function(){println("aSyncSeq -8 ");}
, function(){println("aSyncSeq -9 ");}
, function(){println("aSyncSeq -10 ");}
, function(){println("aSyncSeq -11 ");}
, function(){println("aSyncSeq -12 ");}
, function(){println("aSyncSeq -13 ");}
, function(){println("aSyncSeq -14 ");}
, function(){println("aSyncSeq -15 ");}
, function(){println("aSyncSeq -16 ");}
, function(){println("aSyncSeq -17 ");}
, function(){println("aSyncSeq -18 ");}
, function(){println("aSyncSeq -19 ");}
, function(){println("aSyncSeq -20 ");}
, function(){println("aSyncSeq -21 ");}
, function(){println("aSyncSeq -22 ");}
, function(){println("aSyncSeq -23 ");}
, function(){println("aSyncSeq -24 ");}
, function(){println("aSyncSeq -25 ");}
, function(){println("aSyncSeq -26 ");}
, function(){println("aSyncSeq -27 ");}
, function(){println("aSyncSeq -28 ");}
, function(){println("aSyncSeq -29 ");}
]);
asyncSeq([function(){println("aSyncSeq test-chain -a0 ");}
, function(){println("aSyncSeq test-chain -a1 ");}
, function(){println("aSyncSeq test-chain -a2 ");}
, function(){println("aSyncSeq test-chain -a3 ");}
, function(){println("aSyncSeq test-chain -a4 ");}
, function(){println("aSyncSeq test-chain -a5 ");}
, function(){println("aSyncSeq test-chain -a6 ");}
, function(){println("aSyncSeq test-chain -a7 ");}
, function(){println("aSyncSeq test-chain -a8 ");}
], "test-chain");
asyncSeq([function(){println("aSyncSeq -a0 ");}
, function(){println("aSyncSeq -a1 ");}
, function(){println("aSyncSeq -a2 ");}
, function(){println("aSyncSeq -a3 ");}
, function(){println("aSyncSeq -a4 ");}
, function(){println("aSyncSeq -a5 ");}
, function(){println("aSyncSeq -a6 ");}
, function(){println("aSyncSeq -a7 ");}
, function(){println("aSyncSeq -a8 ");}
]);
}
var textArea = null;
function println(text)
{
if( textArea == null )
{
textArea = document.getElementById("text");
textArea.value = "";
}
textArea.value = textArea.value text "rn";
}
最后,要向大家说一声抱歉,很多只想拿代码的朋友恐怕要失望了,如果你真的不知道怎么处理这些多余的行号,你可以学习一下正则表达式的替换,推荐用UltraEdit。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

Analysis of the role and principle of nohup In Unix and Unix-like operating systems, nohup is a commonly used command that is used to run commands in the background. Even if the user exits the current session or closes the terminal window, the command can still continue to be executed. In this article, we will analyze the function and principle of the nohup command in detail. 1. The role of nohup: Running commands in the background: Through the nohup command, we can let long-running commands continue to execute in the background without being affected by the user exiting the terminal session. This needs to be run

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.

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

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 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

Concurrent and Asynchronous Programming Concurrent programming deals with multiple tasks executing simultaneously, asynchronous programming is a type of concurrent programming in which tasks do not block threads. asyncio is a library for asynchronous programming in python, which allows programs to perform I/O operations without blocking the main thread. Event loop The core of asyncio is the event loop, which monitors I/O events and schedules corresponding tasks. When a coroutine is ready, the event loop executes it until it waits for I/O operations. It then pauses the coroutine and continues executing other coroutines. Coroutines Coroutines are functions that can pause and resume execution. The asyncdef keyword is used to create coroutines. The coroutine uses the await keyword to wait for the I/O operation to complete. The following basics of asyncio

Table of Contents Astar Dapp Staking Principle Staking Revenue Dismantling of Potential Airdrop Projects: AlgemNeurolancheHealthreeAstar Degens DAOVeryLongSwap Staking Strategy & Operation "AstarDapp Staking" has been upgraded to the V3 version at the beginning of this year, and many adjustments have been made to the staking revenue rules. At present, the first staking cycle has ended, and the "voting" sub-cycle of the second staking cycle has just begun. To obtain the "extra reward" benefits, you need to grasp this critical stage (expected to last until June 26, with less than 5 days remaining). I will break down the Astar staking income in detail,
