Code Implementation of the JavaScript asynchronous call framework

Source: Internet
Author: User

In the previous article, we mentioned the implementation of an Async. Operation class for JavaScript asynchronous calls. The callback function is passed through the addCallback method and the callback result is returned through the yield method. Now let's implement this class.

Class Structure

First, let's build a shelf and list all the variables that need to be used. We need an array to save the callback function list. A flag is required to indicate whether the asynchronous operation has been completed. You can also learn IAsyncResult and add a state, allow the implementer of asynchronous operations to expose the custom execution status. Add a variable to save the asynchronous operation result.

 
 
  1. Async = {  
  2.   Operation: {  
  3.     var callbackQueue = [];  
  4.     this.result = undefined;  
  5.     this.state = "waiting";  
  6.     this.completed = false;  
  7.   }  

AddCallback Method

Next, we need to implement the addCallback method. Its job is to put the callback function into callbackQueue. In addition, if the value of completed is true, the asynchronous operation has passed yield, and the callback is called immediately.

 
 
  1. this.yield = function(callback) {  
  2.   callbackQueue.push(callback);  
  3.   if (this.completed) {  
  4.     this.yield(this.result);  
  5.   }  
  6.   return this;  

We assume that the yield method will extract the callback functions in callbackQueue one by one and then call them. Therefore, if compeleted is set to true, you can use the existing result to call yield again, in this way, yield will naturally call the callback function added to callbackQueue this time.

As for the final return this;, just to facilitate jQuery-style chained writing, multiple callback functions can be added consecutively using dot-number separation to implement JavaScript asynchronous calling:

 
 
  1. asyncOperation(argument)  
  2.   .addCallback(firstCallback)  
  3.   .addCallback(secondCallback); 

Yield Method

Finally, we need to implement the yield method. It needs to extract the callback functions in callbackQueue one by one, and then call them again, and ensure that this operation is asynchronous.

 
 
  1. this.yield = function(result) {  
  2.   var self = this;  
  3.   setTimeout(function() {  
  4.     self.result = result;  
  5.     self.state = "completed";  
  6.     self.completed = true;  
  7.     while (callbackQueue.length > 0) {  
  8.       var callback = callbackQueue.shift();  
  9.       callback(self.result);  
  10.     }  
  11.   }, 1);  
  12.   return this;  

By using setTimeout, we ensure that the actual yield operations are performed asynchronously. Then, we update the user-passed yield results and related statuses to the object attributes, and finally traverse callbackQueue to call all the callback functions.

Summary

In this way, a simple JavaScript asynchronous call framework is ready. The complete code is as follows:

 
 
  1. Async = {  
  2.     Operation: function() {  
  3.         var callbackQueue = [];  
  4.         this.result = undefined;  
  5.         this.state = "running";  
  6.         this.completed = false;  
  7.  
  8.         this.yield = function(result) {  
  9.             var self = this;  
  10.             setTimeout(function() {  
  11.                 self.result = result;  
  12.                 self.state = "completed";  
  13.                 self.completed = true;  
  14.  
  15.                 while (callbackQueue.length > 0) {  
  16.                     var callback = callbackQueue.shift();  
  17.                     callback(self.result);  
  18.                 }  
  19.             }, 1);  
  20.             return this;  
  21.         };  
  22.  
  23.         this.addCallback = function(callback) {  
  24.             callbackQueue.push(callback);  
  25.             if (this.completed) {  
  26.                 this.yield(this.result);  
  27.             }  
  28.             return this;  
  29.         };  
  30.     }  
  31. }; 

This framework can well solve the coexistence of synchronous and asynchronous operations in the call stack. Assume that all functions return Async. operation, framework users can use a unified mode to write code and process function return, without having to worry about whether the function actually returns synchronously or asynchronously.

The nested addCallback method can be used to write multiple asynchronous functions in a serial call. However, as the number of nested layers increases, the code will become more and more unattractive:

 
 
  1. firstAsyncOperation().addCallback(function() {  
  2.   secondAsyncOperation().addCallback(function() {  
  3.     thirdAsyncOperation().addCallback(function() {  
  4.       finalSyncOperation();  
  5.     });  
  6.   });  
  7. }); 

Can we change the nested form to jQuery-style chained writing? This is the question to be considered next.

  1. JavaScript asynchronous call framework case design
  2. Description of the JavaScript asynchronous call framework
  3. How to use Javascript + VML to implement process designer
  4. Common JavaScript Regular Expression Verification
  5. 24 tips for beginners of JavaScript

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.