Write a JavaScript Asynchronous call Framework (Part 6

Source: Internet
Author: User
Tags json

We used 5 articles to discuss how to write a JavaScript asynchronous invocation framework (problem & scenario, use case design, code implementation, chained invocation, chained implementations), and now is the time to take a look at how to use it in a variety of common development scenarios.

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.

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:

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:

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.

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;
}

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.