JavaScript asynchronous call framework (Part3-code implementation) _ javascript skills

Source: Internet
Author: User
In the previous article, we talked about implementing an Async. Operation class, passing the callback function through the addCallback method, and returning the callback result 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.

The Code is as follows:


Async = {
Operation :{
Var callbackQueue = [];
This. result = undefined;
This. state = "waiting ";
This. completed = false;
}
}


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.

The Code is as follows:


This. yield = function (callback ){
CallbackQueue. push (callback );
If (this. completed ){
This. yield (this. result );
}
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;, to facilitate jQuery-style chained writing, you can add multiple callback functions consecutively by separating the dots:

The Code is as follows:


AsyncOperation (argument)
. AddCallback (firstCallback)
. 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.

The Code is as follows:


This. yield = function (result ){
Var self = this;
SetTimeout (function (){
Self. result = result;
Self. state = "completed ";
Self. completed = true;
While (callbackQueue. length> 0 ){
Var callback = callbackQueue. shift ();
Callback (self. result );
}
}, 1 );
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, we have completed a simple JavaScript asynchronous call framework. The complete code can be viewed here: asynchronous call framework Async. Operation.
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:

The Code is as follows:


FirstAsyncOperation (). addCallback (function (){
SecondAsyncOperation (). addCallback (function (){
ThirdAsyncOperation (). addCallback (function (){
FinalSyncOperation ();
});
});
});


Can we change the nested form to jQuery-style chained writing? This is the question to be considered next. If you do not want to miss the discussion
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.