JavaScript Asynchronous Invocation Framework (Part 6-instance & mode) _javascript tips

Source: Internet
Author: User
Encapsulating Ajax
The original purpose of design async.operation is to solve the problem that Ajax calls need to pass callback parameters, so we first encapsulate the AJAX request as async.operation. I'm using jquery here, of course, no matter what base library you use, you can do this simple encapsulation when using async.operation.
Copy Code code 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 I invoked, only get and post were needed, and the data was JSON, so I blocked out the other Ajax options provided by jquery and set the data type to JSON. In your project, you can also encapsulate Ajax in a number of ways that simply return async.operation, encapsulating the options provided by jquery in the AJAX layer and no longer exposing these options to the top.

Invoke Ajax
After encapsulating the Ajax, we can begin to focus on the business logic.

Let's say we have a friend object whose get method is used to return a single Buddy object, and the GetAll method is used to return all the Buddy objects. The corresponding two server-side Api,friend interface returns a single buddy JSON, and the Friendlist interface returns a JSON of all buddy names.

First, let's look at how the more basic Get methods are written:
Copy Code code as follows:

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

Is it that simple? Yes, if the server-side API returns a JSON structure that just happens to be the Buddy object structure you want. If the JSON structure and the Buddy object structure are heterogeneous, you might want to add code to map the JSON to objects:
Copy Code code 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 Queues
The next thing we want to write is the GetAll method. Since the Friendlist interface only returns a list of buddy names, we have to call the Get method individually to obtain a specific Buddy object after we get this list. Considering that multiple friend interface calls at the same time may trigger the server's anti attack strategy, resulting in the shutdown of the small black House for some time, so calls to the friend interface must be queued.
Copy Code code 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, and constructs an equal-length asynchronous call queue after acquiring the array, in which the logic of each invocation is the same--take out the name of the first friend in the array, Get the corresponding Buddy object, then put the Buddy object into another array. At the end of the call queue, we append a call to return the array that holds the Buddy object.

In this example, we did not use the call queue to pass the result of the last function to the next function, but it was enough to show the purpose of the call queue--to have multiple low-level asynchronous operations for Ajax requests blocking execution in a fixed order.

Since the underlying asynchronous function returns the Async.operation, you can pass it directly to the next method, or you can wrap the anonymous function over it and pass it to the next method, which requires only one return inside the anonymous function.

delay function
In the example above, queues are used to avoid triggering a server's attack strategy, but sometimes this is not enough. For example, if the server requires at least 500 milliseconds between the two requests, otherwise it is considered an attack, then we are going to insert the interval within the queue.

It is a way to manually join the settimeout in the anonymous function that was called by the next method, but why don't we write an auxiliary function to solve this kind of problem? Let's write an auxiliary method and make it seamless with async.operation.
Copy Code code 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 milliseconds interval between each AJAX request in the GetAll method described above. The addition of a call to wait in the For loop is OK.
Copy Code code 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
With a few simple examples, we learned the common uses of async.operation and how to extend its functionality when needed. Hopefully async.operation can help you improve the code readability of AJAX applications.

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.