jQuery - jQuery Deferred Objects and Promises
Introduction
In web applications, many operations do not complete immediately. Tasks such as loading data from a server, reading files, or waiting for user input take time to finish. These are called asynchronous operations.
jQuery provides Deferred Objects and Promises to manage asynchronous tasks in a structured and reliable way. Instead of writing complex nested callback functions, developers can control execution flow using Deferred and Promise methods.
What is a Deferred Object
A Deferred object is a special jQuery object that represents a task which may complete in the future.
It allows a program to define three possible states:
-
Pending – The task has started but not finished.
-
Resolved – The task completed successfully.
-
Rejected – The task failed or produced an error.
The Deferred object lets developers attach functions that run automatically when the task finishes.
Creating a Deferred Object
A Deferred object is created using the following syntax:
var deferred = $.Deferred();
Now the developer controls when the task succeeds or fails.
Example:
var deferred = $.Deferred();
setTimeout(function(){
deferred.resolve("Data Loaded Successfully");
}, 2000);
deferred.done(function(message){
console.log(message);
});
Explanation:
-
A task runs for 2 seconds.
-
After completion, resolve() is called.
-
The done() function executes automatically.
Deferred Methods
-
resolve()
Marks the operation as successful.
deferred.resolve();
-
reject()
Marks the operation as failed.
deferred.reject();
-
notify()
Sends progress updates while the task is still running.
Promise in jQuery
A Promise is a restricted version of a Deferred object.
It allows developers to observe the result of an operation but prevents them from changing its state.
You can obtain a promise using:
var promise = deferred.promise();
Promises improve security and code organization because external code cannot accidentally resolve or reject the task.
Promise Callback Functions
done()
Runs when the task succeeds.
promise.done(function(){
console.log("Success");
});
fail()
Runs when the task fails.
promise.fail(function(){
console.log("Error occurred");
});
always()
Runs whether the task succeeds or fails.
promise.always(function(){
console.log("Task completed");
});
Using Deferred with AJAX
jQuery AJAX functions already return Promises.
Example:
$.ajax({
url: "data.json"
})
.done(function(data){
console.log("Data received");
})
.fail(function(){
console.log("Request failed");
});
This removes the need for deeply nested callbacks.
Advantages of Deferred and Promises
-
Simplifies asynchronous programming.
-
Avoids callback nesting problems.
-
Improves readability and maintainability.
-
Allows multiple functions to respond to the same task result.
-
Helps manage complex AJAX operations.
Real Life Example
Consider loading multiple resources before displaying a webpage:
-
Load user data
-
Load images
-
Load settings
Deferred objects can wait until all operations finish before continuing execution.
Conclusion
jQuery Deferred Objects and Promises provide a powerful system for handling asynchronous operations. They help developers control execution flow, manage success and failure conditions, and write cleaner and more organized code compared to traditional callback-based programming.