JavaScript asynchronous call framework (Part6-instance & pattern) _ javascript skills

Source: Internet
Author: User
We used five articles to discuss how to compile a JavaScript asynchronous call framework (Question & amp; scenario, case design, code implementation, chain call, and chain implementation ), now, let's take a look at how to use it in various common development scenarios. Encapsulate Ajax
The initial purpose of Async. Operation is to solve the problem of passing the callback parameter in Ajax calls. Therefore, we first encapsulate Ajax requests as Async. Operation. JQuery is used here. Of course, no matter what basic library you use, you can perform this simple encapsulation When Using Async. Operation.

The Code is as follows:


Var Ajax = {};

Ajax. get = function (url, data ){
Var operation = new Async. Operation ();
$. Get (url, data, function (result) {operation. yield (result) ;}, "json ");
Return operation;
};

Ajax. post = function (url, data ){
Var operation = new Async. Operation ();
$. Post (url, data, function (result) {operation. yield (result) ;}, "json ");
Return operation;
};


In the server-side API that I call, only GET and POST are required, and the data is JSON. Therefore, I directly block other Ajax options provided by jQuery, set the data type to JSON. In your project, you can also encapsulate Ajax into several methods that only return Async. operation method, which encapsulates all the options provided by jQuery In the Ajax layer and does not expose these options to the upper layer.

Call Ajax
After encapsulating Ajax, we can concentrate on writing business logic.

Suppose we have a Friend object. Its get method is used to return a single Friend object, while the getAll method is used to return all friends objects. This corresponds to two server-side APIs. The friend interface returns a single friend JSON, while the friendlist interface returns a JSON consisting of all friends.

First, let's take a look at the basic get method:

The Code is as follows:


Function get (name ){
Return Ajax. get ("/friend", "name =" + encodeURIComponent (name ));
}


Is that simple? If the JSON structure returned by the Server API is exactly the structure of your friend object. If the JSON structure and friend object structure are heterogeneous, you may need to add code to map JSON to objects:

The Code is as follows:


Function get (name ){
Var operation = new Async. Operation ()
Ajax. get ("/friend", "name =" + encodeURIComponent (name ))
. AddCallback (function (json ){
Operation. yield (createFriendFromJson (json ));
});
Return operation;
}


Ajax queue
Next we will compile the getAll method. Since the friendlist interface only returns the list of friends names, after obtaining this list, we also need to call the get method one by one to obtain specific friends objects. Considering that multiple calls to the friend interface at the same time may trigger the server's anti-attack policy, resulting in a certain period of time being shut down, the call to the friend interface must be queued.

The Code is as follows:


Function getAll (){
Var operation = new Async. Operation ();
Var friends = [];
Var chain = Async. chain ();
Ajax. get ("/friendlist ","")
. AddCallback (function (json ){
For (var I = 0; I <json. length; I ++ ){
Chain. next (function (){
Return get (json. shift ())
. AddCallback (function (friend) {friends. push (friend );});
});
}
Chain
. Next (function () {operation. yield (friends );})
. Go ();
})
Return operation;
}


Here, we assume that the JSON returned by the friendlist interface is an Array. After obtaining this Array, we construct an equi-long asynchronous call queue, the logic of each call is the same: retrieve the name of the first friend in the Array, use the get method to obtain the corresponding friend object, and then put the friend object into another Array. At the end of the call queue, We append a call to return the Array that saves the friend object.

In this example, we didn't use the call queue to pass the result of the previous function to the next function, however, it is enough to demonstrate the purpose of the call queue-so that multiple asynchronous operations with underlying Ajax requests are executed in a fixed order in blocking mode.

Because the underlying asynchronous function returns Async. operation, you can directly pass it to the next method, or you can wrap it with an anonymous function and then pass it to the next method, while the anonymous function only needs a return internally.

Latency Functions
In the above example, the queue is used to avoid triggering the server's anti-attack policy, but sometimes this is not enough. For example, the server requires a minimum interval of 500 milliseconds between two requests. Otherwise, it is regarded as an attack, so we have to insert this interval in the queue.

Adding setTimeout manually to the anonymous function called by the previous next method is a way, but why don't we write a helper function to solve this problem? Let's write an auxiliary method and seamlessly integrate it with Async. Operation.

The Code is as follows:


Async. wait = function (delay, context ){
Var operation = new Async. Operation ();
SetTimeout (function () {operation. yield (context) ;}, delay );
Return operation;
};

Async. Operation. prototype. wait = function (delay, context ){
This. next (function (context) {return Async. wait (delay, context );});
}


With this helper method, we can easily implement the 500 ms interval between each Ajax request in the above getAll method. Add the wait call to the for loop.

The Code is as follows:


For (var I = 0; I <json. length; I ++ ){
Chain
. Wait (500)
. Next (function (){
Return get (json. shift ())
. AddCallback (function (friend) {friends. push (friend );});
});
}


Summary
Through some simple examples, we learned the common usage of Async. Operation and how to extend its functions when necessary. We hope that Async. Operation can effectively help you improve the code readability of Ajax applications.
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.