In jQuery, a Deferred object is a tool designed to manage asynchronous operations. It represents a task that is not yet complete but will be in the future. It allows you to set up callbacks that will be executed when the task completes, either successfully or with an error.
A Promise object is a simpler, read-only version of a Deferred object. It represents the eventual completion (or failure) of an asynchronous operation and its resulting value. While Deferreds are used to control the state of the task, Promises are used to react to its outcome.
You create a Deferred object using the $.Deferred()
function:
var deferred = $.Deferred();
This deferred
object can be used to handle asynchronous tasks and manage their states.
You can obtain a Promise object from a Deferred object by calling .promise()
:
var promise = deferred.promise();
This promise
object can be used to register callbacks and handle the results of the asynchronous operation.
Deferred objects provide methods to define callbacks for various outcomes:
deferred.done(function(result) {
console.log("Success: " + result);
}).fail(function(error) {
console.log("Error: " + error);
}).progress(function(progress) {
console.log("Progress: " + progress);
});
.done()
: Registers a callback for when the Deferred is resolved successfully..fail()
: Registers a callback for when the Deferred is rejected with an error..progress()
: Registers a callback to handle progress updates.You can manually resolve or reject a Deferred object:
deferred.resolve("Operation completed!");
// or
deferred.reject("Operation failed!");
Here’s how to simulate an asynchronous operation using setTimeout
:
function asyncTask() {
var deferred = $.Deferred();
setTimeout(function() {
deferred.resolve("Task completed successfully!");
}, 2000);
return deferred.promise();
}
asyncTask().done(function(result) {
console.log(result);
});
asyncTask()
returns a Deferred object wrapped in a Promise.setTimeout
simulates an asynchronous task that resolves after 2 seconds..done()
logs the result when the Deferred is resolved.
Task completed successfully!
Deferreds can be chained to handle sequences of asynchronous operations:
function firstTask() {
var deferred = $.Deferred();
setTimeout(function() {
deferred.resolve("First task completed");
}, 1000);
return deferred.promise();
}
function secondTask() {
var deferred = $.Deferred();
setTimeout(function() {
deferred.resolve("Second task completed");
}, 500);
return deferred.promise();
}
firstTask().done(function(result) {
console.log(result);
return secondTask();
}).done(function(result) {
console.log(result);
});
firstTask()
and secondTask()
return Deferred objects..done()
ensures secondTask()
runs only after firstTask()
completes.
First task completed
Second task completed
function failingTask() {
var deferred = $.Deferred();
setTimeout(function() {
deferred.reject("An error occurred!");
}, 1000);
return deferred.promise();
}
failingTask().done(function(result) {
console.log(result);
}).fail(function(error) {
console.log(error);
});
failingTask()
simulates a task that fails..fail()
handles the error scenario.
An error occurred!
Deferreds are often used with AJAX requests to handle asynchronous data fetching:
$.ajax({
url: "https://api.example.com/data",
method: "GET"
}).done(function(data) {
console.log("Data received: " + JSON.stringify(data));
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log("Request failed: " + textStatus);
});
.done()
method processes the successful response..fail()
method handles any errors.You can create and manage your own Deferred objects for various custom asynchronous tasks:
function customDeferredTask() {
var deferred = $.Deferred();
// Simulating an asynchronous task
setTimeout(function() {
deferred.resolve("Custom task complete");
}, 3000);
return deferred.promise();
}
customDeferredTask().done(function(message) {
console.log(message);
});
customDeferredTask()
simulates a task with a 3-second delay..done()
logs the completion message.
Custom task complete
Deferreds and Promises in jQuery provide powerful abstractions for managing asynchronous operations. By understanding how to create, use, and chain Deferreds and Promises, you can handle complex asynchronous workflows with ease.From basic creation and callback definitions to advanced chaining, error handling, and managing multiple tasks, this chapter covers a broad range of topics. By mastering these concepts, you can write more efficient and readable code for asynchronous tasks in your jQuery applications. Happy coding !❤️