What are deferred and promise object in jQuery?

In jQuery, Deferred and Promise objects are used for handling asynchronous operations, such as AJAX requests, animations, or any other tasks that may take time to complete. These objects provide a way to manage and coordinate such operations, making it easier to work with asynchronous code and handle the results when they are available.

Deferred Object

  1. A Deferred object represents a value (or a sequence of values) that may not be available yet but will be at some point in the future.
  2. It provides methods like .resolve(), .reject(), and .notify() to control the state and progress of an asynchronous operation.
  3. You can attach callbacks to a Deferred object using .done(), .fail(), and .progress(). These callbacks are executed when the operation is successful, encounters an error, or reports progress, respectively.
function fetchData() { var deferred = $.Deferred(); // Simulate an AJAX request setTimeout(function() { var data = { message: "Data fetched successfully" }; deferred.resolve(data); }, 2000); return deferred.promise(); } var promise = fetchData(); promise.done(function(data) { console.log(data.message); // Output: Data fetched successfully });

Promise Object

  1. A Promise object represents the eventual result of an asynchronous operation and is returned by a Deferred object's .promise() method.
  2. While you can't directly change the state or progress of a Promise, you can attach callbacks using .then(), which is similar to .done() and .fail().
  3. Promises help make asynchronous code more readable and manageable, allowing you to chain operations and handle success or failure in a clean way.
function fetchData() { return $.ajax({ url: "https://example.com/api/data", method: "GET" }); } fetchData() .then(function(data) { console.log(data); // Handle success }) .catch(function(error) { console.error(error); // Handle error });

Conclusion

Deferred objects are used to create and control asynchronous operations, while Promise objects represent the eventual outcome of those operations. They help streamline the handling of asynchronous tasks, making code more readable and maintainable.