jquery manages Ajax asynchronous _jquery via deferred objects

Source: Internet
Author: User

Today, I'd like to share with you a-deferred object in jquery. In fact, a new feature introduced from the jquery version 1.5.0----Deferred objects. However, it may not be used in the actual development process, so not too much attention.

What is a deferred object?

In the process of developing a Web site, we often experience some very lengthy javascript operations. There are both asynchronous operations (such as AJAX reading Server data), and synchronous operations (such as traversing a large array), none of which can immediately result.

The usual practice is to specify a callback function (callback) for them. That is, in advance, which functions should be called once they are finished.

However, in terms of callback functions, jquery has a very weak function. To change this, the jquery development team designed the deferred object.

Simply put, the deferred object is the callback function solution for jquery. In English, defer means "delay", so the meaning of the deferred object is "delay" to a certain point in the future.

Let's not say the concept of deferred first, we'll look at an example first.

Remember when beginners, encountered an example, first to Ajax request an interface (A.json), from the returned data to obtain a ID1 value. Then request an interface (B.json) to obtain ID2, and finally the two ID values need to be manipulated simultaneously.

Error solution

At that time beginners, first thought of the scheme (now think, very naïve ... )

var id1, Id2;
$.ajax ({
URL: ' a.js ',
dataType: ' json ',
type: ' Get ',
success:function (d) {
id1 = d.item.id;
}
});
$.ajax ({
URL: ' b.js ',
dataType: ' json ',
type: ' Get ',
success:function (d) {
id2 = d.item.id;
}
})

Because at that time, has not understood the asynchronous concept, therefore thought that, the second time Ajax time ID already has the value, but after running only then discovered, the variable ID actually did not have the assignment value. Want to test the code above, click here

That's the moment I really understand: AJAX is an asynchronous!!!.

The method of the Fool

found that the above method can not be used after the analysis of the pop-up undefined because the ID has not been assigned before, then I guarantee that before the pop-up ID assigned to solve it? OK, so I thought of the following method:

var id1; 
$.ajax ({
URL: '/test/json/a.js ',
dataType: ' json ',
type: ' Get ',
success:function (d) {
id1 = D.item.id;
$.ajax ({
URL: '/test/json/b.js ',
dataType: ' json ',
type: ' Get ',
success:function (f) {
Id2 = F.item.id;
Alert (' id1= ' +id1+ ', ' + ' id2= ' + Id2);}}
);

The logic is correct, but it's always weird, what if you need to nest 3 layers? 4 floors? Ajax embedded in Ajax, if the data are many, slow access, nesting more layers, can lead to performance degradation, affect the user experience, poor code maintenance and so on. Therefore, this method is generally not recommended. In short, this kind of writing makes me difficult to accept.

So reasoning, feel wrong ... Then at that time in a front-end group, ask all kinds of Daniel, until a Daniel told me to let me Baidu deferred, and then seriously studied, feel good.

Using the Deferred object

Introduction to deferred objects

Deferred is an object of expansion in jquery (1.5.0 version supports deferred). Defer means "delay", so the meaning of the deferred object is "delay" to a certain point in the future.

Simply put, the deferred object is the callback function solution for jquery.

Simply put, the deferred object is used to manage asynchronous operations, and Ajax is an asynchronous operation.

Deferred basic syntax

Deferred lets Ajax support the new writing code as follows:

$.ajax ({
URL: '/test/json/a.js ',
dataType: ' json ',
type: ' Get '
})
. Done (function () {
Alert ("Success!") ");
})
. Fail (function () {
alert ("Failed ...");

We should all know that. Now in the editor type Ajax, and then enter, the hint of the AJAX syntax structure is such a chained style.

The done function is the return function of Ajax request success;

The Fail function is the callback function that failed the AJAX request.

How to use deferred solution

var ajax1 = $.ajax ({
URL: '/test/json/a.js ',
dataType: ' json ',
type: ' Get '
});
var ajax2 = $.ajax ({
URL: '/test/json/b.js ',
dataType: ' json ',
type: ' Get ',
});
$.when (AJAX1,AJAX2). Done (function (d1,d2) {
var id1 = d1[0].item.id;
var id2 = d2[0].item.id;
Alert (' id1= ' +id1+ ', ' + ' id2= ' + id2);
}). Fail (function () {
alert (' Error ');

It's worth mentioning that the parameters of the function in the code above correspond to the data returned by each of the previous AJAX requests

In the code above, the When method of the deferred object is used.

Its description is:

Provides a way to execute a callback function for one or more objects.

Here the Ajax1 and Ajax2 are deferred objects, done and fail is the callback function. The code above means:

Executes the done function only when two AJAX requests successfully return data, and executes the FAIL function whenever a request is unsuccessful.

Also worth mentioning is: $.when method parameters, only support deferred object, and Ajax return is deferred object. `

This has already achieved the above requirements. Requests two interfaces, obtains two data, when all succeeds, two data processing simultaneously. And this kind of chain style writing, lets the reader at a glance, and facilitates the maintenance extension.

Deferred method Rollup

The method mentioned

$. Deferred (): Generates a Deferred object.

$.when () specifies a callback function for multiple operations.

Deferred.done (): Specifies a callback function after a successful operation

Deferred.fail (): Specifies the callback function after the operation failed

A method not mentioned

Deferred.resolve () method and Deferred.reject () method

The deferred object performs a callback function before it has an execution state that has a total of three ——— incomplete, completed, and failed.

Incomplete state, the wait is continued or the callback function specified by progress () is executed.

Completed state, the callback function specified by the done () method is executed.

Has failed status, the callback function specified by the fail () method is executed.

So the Deferred.resolve () method here is to manually change the state of the deferred object to completed, and then execute the Done method; The Deferred.reject () method is to manually change the status to failed and then execute the Fail method.

Here's an example:

var defer = $. Deferred (); Create a new Deferred object
var wait = function (defer) {
var tasks = function () {
defer.resolve ();//Change Deferred Object Alert for completed status
("execution completed!")    ");
};
SetTimeout (tasks,5000);
return defer;
};
$.when (defer)
. Done (function () {
alert ("succeed"); 
})
. Fail (function () {
alert ("failed"); 

Results: Wait 5 seconds, first eject "succeed", in the pop-up "execution completed!" ”。

Analyze the code execution process:

$.when () inside the parameter is a wait function, that is, a deferred object, so you can continue to perform the settimeout function, wait for 5s, perform the tasks function, and then manually changed the state to "completed", so do the Done method, pop-up "succeed "And then pops up" execution completed! ”。

Deferred.then (): Sometimes for the sake of convenience, can be done () and fail () together to write, this is the then () method.

function Successfun () {
alert ("yes");
}
function Failfun () {
alert (' fail ');
}
$.when ($.ajax ({
URL: '/test/json/a.js ',
dataType: ' json ',
type: ' Get '
})

When the then method has only one parameter, it is equivalent to the Done method. When there are two parameters, the first equivalent to the Done method, and the second equivalent to the Fail method.

Summarize

The deferred object, by controlling a variety of callback functions for an AJAX request, makes jquery writing Ajax simple, easy to maintain, and easy to expand.

The above is a small set to introduce jquery through the deferred object management Ajax asynchronous knowledge, hope for everyone to help, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.