Origin
Do not understand the JS async students see the following example:
for (var i = 0; i < 5; i++) {
Simulates an asynchronous operation , = { console.log (i) ; );}
The result we want is: 0,1,2,3,4
The result was unexpected: 5,5,5,5,5
Analysis
JS is characterized by single-threaded asynchronous non-clogging. Need to understand this sentence: JS for asynchronous operations, do not stop to wait for the previous asynchronous operation to complete before the next asynchronous operation.
If you want to achieve sequential execution, you can only use callbacks: that is, when the last asynchronous operation completes, the next asynchronous operation is called.
How do you do it, as in the loop above?
Workaround 1
To resolve a loop's callback nesting problem by calling itself
function Sync (i) { = = {if (i < 5) { console.log (i); I+ +; Sync (i); } );} Sync (0)
Workaround 2
Using Await/async
Advantages: Intuitive, in line with synchronous programming thinking. Actually, it's an asynchronous callback.
Cons: Most browser downloads are not yet supported. Need to be used in conjunction with promise, need to write two functions
Server-side node. JS Support. The following code can be run in the latest version of the Chrome browser:
Const F = (i) + = {returnnew Promise (( Resolve, reject) + = = { resolve (i); ); = Async () = { for (var i = 0; i < 5; i++) { = await f (i ); Console.log (t); }}; Testasync ();
Workaround 3
Waiting to be added ...
JavaScript's asynchronous Programming solution collection