search
HomeWeb Front-endJS Tutorialjquery basic tutorial: How to use deferred objects_jquery

1. What is a deferred object?

In the process of developing websites, we often encounter certain JavaScript operations that take a long time. Among them, there are both asynchronous operations (such as ajax reading server data) and synchronous operations (such as traversing a large array), and the results are not available immediately.

The usual approach is to specify callback functions for them. That is, specify in advance which functions should be called once they have finished running.

However, jQuery is very weak when it comes to callback functions. In order to change this, the jQuery development team designed the deferred object.

To put it simply, the deferred object is jQuery’s callback function solution. In English, defer means "delay", so the meaning of a deferred object is to "delay" execution until a certain point in the future.

It solves the problem of how to handle time-consuming operations, provides better control over those operations, and a unified programming interface. Its main functions can be summarized into four points. Below we will learn step by step through sample code.

2. Chain writing method of ajax operation

First, let’s review the traditional way of writing jQuery’s ajax operation:

Copy code The code is as follows:

$.ajax({
url: "test .html",
success: function(){
alert("Haha, successful!");

},
error:function(){
alert("An error occurred!");
}

});

In the above code, $.ajax() accepts an object parameter. This object contains two methods: the success method specifies the callback function after the operation is successful, and the error method specifies the callback function after the operation fails.

After the $.ajax() operation is completed, if you are using a version of jQuery lower than 1.5.0, the XHR object will be returned and you cannot perform chain operations; if the version is higher than 1.5.0, the returned Deferred objects can be chained.

Now, the new way of writing is like this:

Copy the code The code is as follows:

$.ajax("test.html")

.done(function(){ alert("Haha, successful!"); })

.fail(function(){ alert("Error!"); });

As you can see, done() is equivalent to the success method, and fail() is equivalent to the error method. After adopting the chain writing method, the readability of the code is greatly improved.

3. Specify multiple callback functions for the same operation

One of the great benefits of the deferred object is that it allows you to add multiple callback functions freely.

Taking the above code as an example, if after the ajax operation is successful, in addition to the original callback function, I also want to run another callback function, what should I do?

It’s very simple, just add it at the end.

Copy code The code is as follows:

$.ajax("test.html")
.done(function(){ alert("Haha, successful!");} )
.fail(function(){ alert("An error occurred!"); } )
.done(function( ){ alert("Second callback function!");} );


You can add as many callback functions as you like, and they will be executed in the order they are added.

4. Specify callback functions for multiple operations

Another great benefit of the deferred object is that it allows you to specify a callback function for multiple events, which is not possible with traditional writing.

Please look at the following code, which uses a new method $.when():

Copy code The code is as follows:

$.when($.ajax("test1.html "), $.ajax("test2.html"))
.done(function(){ alert("Haha, successful!"); })
.fail(function(){ alert(" Something went wrong! "); });


The meaning of this code is to first perform two operations $.ajax("test1.html") and $.ajax("test2 .html"), if all succeed, the callback function specified by done() will be executed; if one fails or both fail, the callback function specified by fail() will be executed.

5. Callback function interface for common operations (Part 1)

The biggest advantage of the deferred object is that it extends this set of callback function interfaces from ajax operations to all operations. In other words, any operation - whether it is an ajax operation or a local operation, whether it is an asynchronous operation or a synchronous operation - can use various methods of the deferred object to specify a callback function.

Let’s look at a specific example. Suppose there is a time-consuming operation wait:

Copy code The code is as follows:

var wait = function(){

var tasks = function(){

alert("Execution completed!");

};

setTimeout(tasks,5000);

};



We specify a callback function for it. What should we do?

Naturally, you will think that you can use $.when():

Copy code The code is as follows:

$.when(wait())

.done(function(){ alert("Haha, successful!"); })

.fail(function(){ alert("Error!"); });

However, if written like this, the done() method will be executed immediately and will not function as a callback function. The reason is that the parameters of $.when() can only be deferred objects, so wait() must be rewritten:

Copy code The code is as follows:

var dtd = $.Deferred(); // Create a new deferred object

var wait = function(dtd){

var tasks = function(){

alert("Execution completed!");

dtd.resolve(); // Change the execution status of the deferred object

};

setTimeout(tasks,5000);

return dtd;

};

Now, the wait() function returns a deferred object, so chain operations can be added.

Copy code The code is as follows:

$.when(wait(dtd))

.done(function(){ alert("Haha, successful!"); })

.fail(function(){ alert("Error!"); });

After the wait() function is run, the callback function specified by the done() method will automatically run.

6. deferred.resolve() method and deferred.reject() method

If you look carefully, you will find that there is another place in the wait() function above that I did not explain. That's what dtd.resolve() does?

To clarify this issue, we need to introduce a new concept "execution state". jQuery stipulates that deferred objects have three execution states - unfinished, completed and failed. If the execution status is "completed" (resolved), the deferred object immediately calls the callback function specified by the done() method; if the execution status is "failed", the callback function specified by the fail() method is called; if the execution status is "unsuccessful" Completed", continue to wait, or call the callback function specified by the progress() method (added in jQuery 1.7 version).

During the ajax operation in the previous part, the deferred object will automatically change its execution status based on the return result; however, in the wait() function, this execution status must be manually specified by the programmer. The meaning of dtd.resolve() is to change the execution status of the dtd object from "unfinished" to "completed", thus triggering the done() method.

Similarly, there is also a deferred.reject() method, which changes the execution status of the dtd object from "incomplete" to "failed", thereby triggering the fail() method.

Copy code The code is as follows:

var dtd = $.Deferred(); // New A Deferred object

var wait = function(dtd){

var tasks = function(){

alert("Execution completed!");

dtd.reject(); // Change the execution status of the Deferred object

};

setTimeout(tasks,5000);

return dtd;

};

$.when(wait(dtd))

.done(function(){ alert("Haha, successful!"); })

.fail(function(){ alert("Error!"); });

7. deferred.promise() method

There are still problems with the way of writing above. That is, dtd is a global object, so its execution status can be changed from the outside.

Please look at the code below:

Copy the code The code is as follows:

var dtd = $.Deferred(); // Create a new Deferred object

var wait = function(dtd){

var tasks = function(){

alert("Execution completed!");

dtd.resolve(); // Change the execution status of the Deferred object

};

setTimeout(tasks,5000);

return dtd;

};

$.when(wait(dtd))

.done(function(){ alert("Haha, successful!"); })

.fail(function(){ alert("Error!"); });

dtd.resolve();

I added a line of dtd.resolve() at the end of the code, which changed the execution status of the dtd object, thus causing the done() method to be executed immediately, and the "Haha, successful!" prompt box popped up, etc. 5 After a few seconds, the "Execution Completed!" prompt box will pop up.

To avoid this situation, jQuery provides the deferred.promise() method. Its function is to return another deferred object on the original deferred object. The latter only opens methods that are not related to changing the execution status (such as the done() method and fail() method), and blocks methods related to changing the execution status ( Such as resolve() method and reject() method), so that the execution status cannot be changed.

Please look at the code below:

Copy the code The code is as follows:

var dtd = $.Deferred(); // Create a new Deferred object

var wait = function(dtd){

var tasks = function(){

alert("Execution completed!");

dtd.resolve(); // Change the execution status of the Deferred object

};

setTimeout(tasks,5000);

return dtd.promise(); // Return promise object

};

var d = wait(dtd); // Create a new d object and operate on this object instead

$.when(d)

.done(function(){ alert("Haha, successful!"); })

.fail(function(){ alert("Error!"); });

d.resolve(); // At this time, this statement is invalid



In the above code, the wait() function returns a promise object. Then, we bind the callback function to this object instead of the original deferred object. The advantage of this is that the execution status of this object cannot be changed. If you want to change the execution status, you can only operate the original deferred object.

However, a better way to write it is as pointed out by allenm, to turn the dtd object into the internal object of the wait() function.

Copy code The code is as follows:

var wait = function(dtd){

var dtd = $.Deferred(); //Within the function, create a new Deferred object

var tasks = function(){

alert("Execution completed!");

dtd.resolve(); // Change the execution status of the Deferred object

};

setTimeout(tasks,5000);

return dtd.promise(); // Return promise object

};

$.when(wait())

.done(function(){ alert("Haha, successful!"); })

.fail(function(){ alert("Error!"); });



8. Callback function interface for normal operations (middle)

Another way to prevent the execution state from being changed externally is to use the constructor function $.Deferred() of the deferred object.

At this time, the wait function remains unchanged, and we directly pass it into $.Deferred():

Copy code The code is as follows:

$.Deferred(wait)

.done(function(){ alert("Haha, successful!"); })

.fail(function(){ alert("Error!"); });

jQuery stipulates that $.Deferred() can accept a function name (note, it is a function name) as a parameter, and the deferred object generated by $.Deferred() will be used as the default parameter of this function.

9. Callback function interface for common operations (Part 2)

In addition to the above two methods, we can also deploy the deferred interface directly on the wait object.

Copy code The code is as follows:

var dtd = $.Deferred(); // Generate Deferred object

var wait = function(dtd){

var tasks = function(){

alert("Execution completed!");

dtd.resolve(); // Change the execution status of the Deferred object

};

setTimeout(tasks,5000);

};

dtd.promise(wait);

wait.done(function(){ alert("Haha, successful!"); })

.fail(function(){ alert("Error!"); });

wait(dtd);

The key here is the line dtd.promise(wait), which is used to deploy the Deferred interface on the wait object. It is precisely because of this line that done() and fail() can be called directly on wait later.

10. Summary: Methods of deferred objects

We have already talked about the various methods of deferred objects. Here is a summary:

(1) $.Deferred() generates a deferred object.

(2) deferred.done() specifies the callback function when the operation is successful

(3) deferred.fail() specifies the callback function when the operation fails

(4) When deferred.promise() has no parameters, it returns a new deferred object, and the running status of the object cannot be changed; when it accepts parameters, it serves to deploy the deferred interface on the parameter object.

(5) deferred.resolve() Manually changes the running status of the deferred object to "Completed", thus triggering the done() method immediately.

(6) deferred.reject() This method is exactly the opposite of deferred.resolve(). After being called, the running status of the deferred object will be changed to "failed", thus triggering the fail() method immediately.

(7) $.when() specifies callback functions for multiple operations.

In addition to these methods, the deferred object also has two important methods, which are not covered in the above tutorial.

(8)deferred.then()

Sometimes to save trouble, done() and fail() can be written together. This is the then() method.

$.when($.ajax( "/main.php" ))

.then(successFunc, failureFunc );

If then() has two parameters, then the first parameter is the callback function of the done() method, and the second parameter is the callback method of the fail() method. If then() has only one parameter, it is equivalent to done().

(9)deferred.always()

This method is also used to specify the callback function. Its function is that no matter whether deferred.resolve() or deferred.reject() is called, it will always be executed in the end.

Copy code The code is as follows:

$.ajax( "test.html" )

.always( function() { alert("Executed!");} );

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool