DEV Community

Cover image for Deferred and Promise Object in jQuery
Aryan Dev Shourie
Aryan Dev Shourie

Posted on

Deferred and Promise Object in jQuery

jQuery is an open-source JavaScript library that simplifies the interactions between an HTML/CSS document, or more precisely the Document Object Model (DOM), and JavaScript. The only library available today that meets the needs of both designers and programmers is jQuery.

Deferred Object

The Deferred Object in jQuery is an object that can create a Promise and change its state to resolved or rejected. It is created when a function that performs an asynchronous task is called.

The basic syntax of using the Deferred Object is -

var deferred = $.Deferred();

deferred.done(function(result) {
    // success callback
}).fail(function(error) {
    // failure callback
}).progress(function(progress) {
    // progress callback
});
Enter fullscreen mode Exit fullscreen mode

Promise Object

The Promise Object is a promise about a future value. It can be used to register callbacks that will be executed when the asynchronous task is completed successfully.

The basic syntax of using the Promise Object is -

var promise = $.ajax({url: 'example.com/api/data'});

promise.done(function(result) {
    // success callback
}).fail(function(error) {
    // failure callback
}).always(function() {
    // callback to be executed regardless of success or failure
});
Enter fullscreen mode Exit fullscreen mode

deferred and promise

Methods used in Deferred Object -

  • resolve([args]): It resolves the deferred object and triggers all the successful callbacks.

  • reject([args]): It rejects the deferred object and triggers all the failed callbacks.

  • done(callback): It registers a callback to be executed when the deferred object is resolved successfully.

  • fail(callback): It registers a callback to be executed when the deferred object is rejected.

  • progress(callback): It registers a callback to be executed when the deferred object sends a progress update.

  • always(callback): It registers a callback to be executed regardless of whether the deferred object is resolved or rejected.

Methods used in Promise Object -

  • done(callback): It registers a callback to be executed when the promise object is resolved successfully.

  • fail(callback): It registers a callback to be executed when the promise object is rejected.

  • always(callback): It registers a callback to be executed regardless of whether the promise object is resolved or rejected.

  • then(successCallback, failureCallback): It registers the success and failure callbacks all at once.

  • catch(failureCallback): It registers a callback to be executed when the promise object is rejected.

Including jQuery in the project:

There are multiple ways to start using jQuery in your project:

  • Use the Google-hosted/Microsoft-hosted Content Delivery Network (CDN) to include a version of jQuery.

  • Download your own version of jQuery from the official jQuery website and host it on the server or the local filesystem.

cdn

Example 1

In this example, we will see the working of the Deferred object using jQuery.

Write the following code in your HTML file :

<!DOCTYPE html>
<html>
<head>
    <title>Deferred Object Example</title>
    <script src=
"https://code.jquery.com/jquery-3.6.0.min.js">
    </script>
</head>        

<body>
    <h1>This is an example of Deferred Object in jQuery</h1> 
    <h3>welcome to DEV</h3>
    <div id="result"></div>
    <script>
        function fetchData() {
            var deferred = $.Deferred();

            // Simulate an asynchronous operation 
            // that takes 3 seconds
            setTimeout(function() {
              var data = { id: 123, name: "John" };
              deferred.resolve(data);
            }, 3000);

            return deferred.promise();
        }

        $(document).ready(function() {
            // Call the fetchData function and 
            // register callbacks for success and failure
            fetchData().done(function(data) {
                $("#result").text("Data retrieved: " 
                                  + JSON.stringify(data));
            }).fail(function(error) {
                $("#result").text("Error: " + error);
            });
        });
    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

OUTPUT:

deferred

  1. The JavaScript code begins with a function called fetchData(). This function creates a new Deferred object using $.Deferred() and assigns it to the deferred variable.
  2. Inside the fetchData() function, there is a simulated asynchronous operation represented by the setTimeout function. It delays the execution for 3 seconds and then resolves the Deferred object with a data object containing an ID and a name.
  3. Inside the $(document).ready() function, the fetchData() function is called. The returned promise is used to attach callbacks using the .done() and .fail() methods.

Example 2

In this example, we will see the working of a Promise object using jQuery.

Write the following code in your HTML file :

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Promise Object Example</title>
</head>
<body>
    <h1>This is an example of Promise object in jQuery</h1> 
    <h3>welcome to DEV</h3>

    <div id="data"></div>

    <script>
        function fetchData() {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    const data = { id: 1, name: 'John Doe' };
                    // simulate a successful API call
                    resolve(data);
                    // simulate an error response from the API
                    // reject(new Error('Failed to fetch data'));
                }, 2000);
            });
        }

        fetchData().then((data) => {
            const dataDiv = document.getElementById('data');
            dataDiv.innerText = JSON.stringify(data);
         }).catch((error) => {
            console.error('Error:', error);
        });
    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

OUTPUT:

promise

  1. The JavaScript code defines a function fetchData(). In this function, a new Promise object is created using the Promise constructor.
  2. The Promise constructor takes a callback function with 2 parameters - resolve and reject. These parameters are functions used to indicate the success or failure of the asynchronous operation.
  3. Outside the fetchData() function, the Promise object is used to attach callbacks using the .then() and .catch() methods.

jqjs

Advantages and Disadvantages of Deferred Object -

Advantages:

  • The use of Deferred objects allows the users to easily combine the asynchronous operations together.

  • The Deferred objects provide a consistent interface for handling both successful and failed asynchronous operations.

Disadvantages:

  • The Deferred object is exclusive to jQuery, so it can't be used in other JavaScript frameworks.

  • Using the Deferred objects can add some overhead to the code, both in terms of processing time and memory usage.

Advantages and Disadvantages of Promise Object -

Advantages:

  • Promises can be easily chained or combined together. This makes it simpler to handle multiple asynchronous operations.

  • Promises provide a more standardized interface for handling asynchronous operations as compared to callbacks and deferred objects.

Disadvantages:

  • Promises do not have built-in support for canceling asynchronous operations, which can be problematic in some scenarios.

  • The syntax for working with promises can be more complex as compared to other approaches.

And thats it! You have successfully learnt about the Deferred and Promise objects in jQuery!

Connect with me on Linkedin :- Linkedin

Do check out my Github for amazing projects:- Github

View my Personal Portfolio :- Aryan's Portfolio

Top comments (2)

Collapse
 
navyaarora01 profile image
Navya Arora

Very well explained!!

Collapse
 
aryan_shourie profile image
Aryan Dev Shourie

Thanks!!