Home > Web Front-end > JS Tutorial > Introduction to the principles and implementation techniques of asynchronous javascript_javascript techniques

Introduction to the principles and implementation techniques of asynchronous javascript_javascript techniques

WBOY
Release: 2016-05-16 17:48:38
Original
1177 people have browsed it

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:

Copy code The code is as follows:

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:
Copy code The code is 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:
Copy code The 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:
Copy code The code 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.
Copy code The code is as follows:

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:
Copy code The code is 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。
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