JavaScript's asynchronous Programming solution collection

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.