Deferred and Promises are tools provided by jQuery to handle asynchronous tasks, such as AJAX requests, animations, or other operations that take time to complete. They simplify the management of callbacks and provide a clean way to chain asynchronous operations.
What is Deferred
?
A Deferred object is a way to manage the success, failure, and progress of asynchronous tasks. It can be used to:
- Attach multiple callbacks (success, failure, progress).
- Chain multiple asynchronous actions.
- Trigger actions when an operation succeeds or fails.
Basic Methods of a Deferred Object
Method | Description |
---|---|
$.Deferred() |
Creates a new Deferred object. |
resolve() |
Marks the Deferred object as successful. |
reject() |
Marks the Deferred object as failed. |
done() |
Attaches a success callback. |
fail() |
Attaches a failure callback. |
always() |
Attaches a callback that runs regardless of success or failure. |
then() |
Attaches both success and failure callbacks, and allows chaining of operations. |
Example 1: Basic Use of $.Deferred
<!DOCTYPE html> <html> <head> <title>jQuery Deferred Example</title> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> </head> <body> <div id="output"></div> <script> $(document).ready(function() { function asyncTask() { var deferred = $.Deferred(); setTimeout(function() { var isSuccess = Math.random() > 0.5; // Random success or failure if (isSuccess) { deferred.resolve("Task succeeded!"); } else { deferred.reject("Task failed!"); } }, 2000); return deferred.promise(); // Return a promise } asyncTask() .done(function(message) { $("#output").text("Success: " + message); }) .fail(function(error) { $("#output").text("Error: " + error); }) .always(function() { console.log("Task completed (success or failure)."); }); }); </script> </body> </html>
What is a Promise
?
A Promise is an immutable object that represents the eventual completion or failure of an asynchronous operation. In jQuery, the Deferred.promise()
method generates a Promise object. Unlike a Deferred object, a Promise can only be used to attach callbacks and not to resolve or reject the operation.