What is JavaScript asynchronous programming?

Source: Internet
Author: User

This may be a deep topic. What is Asynchronization?

In general, asynchronous execution is delayed in javascript. Strictly speaking, the asynchronous programming capabilities in javascript are provided by BOM and DOM, such as setTimeout, XMLHttpRequest, DOM event mechanism, newly added webwork and postMessage in html5. These things share a common feature: they have a callback function to implement control inversion. As control reversal is a more profound problem, I don't want to expand it here. However, it can be confirmed that the existence of callback functions interrupts the original Execution Process and enables them to appear and execute at the appropriate time. This is a very convenient mode. Compared with proactive Round Robin, you know how energy-saving it is. In synchronous programming, the code is basically executed from top to bottom. In asynchronous programming, some code must be written to the callback function. If there is dependency between codes, the callback function sets the callback function, this nested structure will be a hell of a lot for future maintenance. There is another situation that we have to deal with. try... catch cannot catch exceptions that occur several milliseconds later. In addition, except setTimeout, asynchronous programming is basically undertaken by the event mechanism. It is basically unknown when their callback functions occur. It may be because of a system-level error in the background that no response can be sent, or, the system is busy and cannot respond at half past one. In both cases, we must also provide a policy to interrupt this operation, that is, the so-called abort, these are all topics to be processed by asynchronous programming.

 
 
  1. $. Post ("/foo. json", function (dataOfFoo) {// Ajax callback with multi-layer nested Structure
  2. $. Post ("/bar. json", function (dataOfBar ){
  3. $. Post ("/baz. json", function (dataOfBaz ){
  4. Alert ([dataOfFoo, dataOfBar, dataOfBaz]);
  5. });
  6. });
  7. });
 
 
  1. Function throwError (){
  2. Throw new Error ('error ');
  3. }
  4. Try {
  5. SetTimeout (throwError, 3000 );
  6. } Catch (e ){
  7. Alert (e); // exceptions cannot be captured.
  8. }

Because such a requirement is met at any time in javascript programming, the implementation of the relevant lightweight API is the top priority. As mentioned above, it only needs to have the following functions, can store a set of callback functions (domReary, multi-cast events, special effects), and execute all the callback functions at a specific time, if an error occurs, the corresponding processing function (negative callback) can be triggered, the entire operation can be aborted, and the operation can be initiated from the disconnection. If more requests are required, we also want to switch from serial to parallel, from parallel to serial. You may not understand many concepts, do you? But these are necessary to get a good special effect. If you have ever played back-end JS, you must have heard of node. js. Now it is almost synonymous with it. Route distribution and I/O operations are asynchronous and event-driven. In order to implement elegant asynchronous programming, the experts are very busy with their respective solutions, such as do. js. step. js, async. js, flow. js ......, It cannot be applied to the front-end. Therefore, we need a suitable front-end solution.

One thing we need to understand is that, as you think, people have already studied it and have provided solutions. Mochikit, one of the top ten javascript frameworks, was used to get Deferred from Python's Twisted library, and later learned from dojo. Now you can see that the same things appear on jQuery1.5 again. However, Mochikit's Deferred also has an unknown branch, which was developed by Japanese Daniel cho45 (what BigInt does he do at the same time, cross-browser Testing, fame follows amachang, uupaa, edvakf, and nanto), called JSDeferred. First, Deferred of the dojo faction (including jQuery) has been invincible, and has developed a set of specifications with Common. js. What promises, then, and when were both developed at that time, and jQuer basically accepted them all. Another branch, cho45's JSDeferred, has a very strange idea. Instead of using arrays to load callback functions, it uses setTimeout and image. asynchronous mechanisms such as onload and postMessage cleverly send maintenance queues back to the browser itself. Although there are fatal defects, their ease of use is also favored by the Japanese JS community, my Deferred object has basically evolved from it. Deferred is usually called asynchronous queuing, because they really need two groups of queues consisting of callback.

Before we move out of the asynchronous queue, let's see how the normal queue achieves latency.

 
 
  1. var Queue = function(){  
  2.       this.list = []  
  3.     }  
  4.     Queue.prototype = {  
  5.       constructor:Queue,  
  6.       queue:function(fn) {  
  7.         this.list.push(fn)  
  8.         return this;  
  9.       },  
  10.       dequeue:function(){  
  11.        var fn = this.list.shift()||function(){};  
  12.        fn.call(this)  
  13.       }  
  14.     }  

Call it like this:

 
 
  1. var q = new Queue;  
  2.     q.queue(function(){  
  3.       log(1)  
  4.     }).queue(function(){  
  5.       log(2)  
  6.     }).queue(function(){  
  7.       log(3)  
  8.     });  
  9.     while(q.list.length){  
  10.       q.dequeune();  
  11.     }  

But this is synchronous. To be asynchronous, we need to use setTimeout,

 
 
  1. var el = document.getElementById("test");  
  2. var q = new Queue();  
  3. q.queue(function(){  
  4.   var self = this;  
  5.   el.innerHTML = 1 
  6.   setTimeout(function(){  
  7.     self.dequeue()  
  8.   },1000);  
  9. }).queue(function(){  
  10.   var self = this;  
  11.   el.innerHTML = 2 
  12.   setTimeout(function(){  
  13.     self.dequeue()  
  14.   },1000);  
  15. }).queue(function(){  
  16.   var self = this;  
  17.   el.innerHTML = 3 
  18.   setTimeout(function(){  
  19.     self.dequeue()  
  20.   },1000);  
  21. }).dequeue()  

As you can see, writing is absolutely unfriendly. We need to round the setTimeout to the Queue class, and make some modifications to the queue. Instead of executing only one function, all callbacks in the Queue are usually operated, for example, domReay.

 
 
  1. var Queue = function(){  
  2.   this.list = []  
  3. }  
  4. Queue.prototype = {  
  5.   constructor:Queue,  
  6.   queue:function(fn) {  
  7.     this.list.push(fn)  
  8.     return this;  
  9.   },  
  10.   wait:function(ms){  
  11.     this.list.push(ms)  
  12.     return this;  
  13.   },  
  14.   dequeue:function(){  
  15.     var self = this, list = self.list;  
  16.     var el = list.shift()||function(){};  
  17.     if(typeof el == "number"){  
  18.       setTimeout(function(){  
  19.         self.dequeue();  
  20.       },el);  
  21.     }else if(typeof el == "function") {  
  22.       el.call(this)  
  23.       if(list.length)  
  24.         self.dequeue();  
  25.     }  
  26.   }  
  27. }  

Great, if we can freely control the interval of each callback, it will become very simple for the animation effect. However, this Queue class is far from our initial goal. Ajax, multi-vote events, and domReay all belong to it, so it needs to use APIs with stronger applicability. People who have used dojo know that its Deferred is like a DNA chromosome, which is a dual line and can capture exceptions that are not on the same time line, in addition, these queues cannot be used up once like sanitary chopsticks, so that they cannot support the implementation of multiple voting events. To implement these functions, you need a complicated one. I will introduce my asynchronous queues in the second part to see how it elegantly solves these problems.

Original article: http://www.cnblogs.com/rubylouvre/archive/2011/03/14/1982699.html

Related Article

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.