What are deferred and promise object in jQuery ?
Last Updated :
30 Jul, 2024
In this article, we will see the deferred and promise object in jQuery, along with understanding their basic implementation and the differences between them.
Deferred objects are a fundamental part of the jQuery library, used for handling asynchronous requests and operations. They provide a way to trigger callbacks when an operation is either completed or failed and can be chained together to create complex asynchronous flows. Deferred objects are a representation of an operation that may not have been completed yet. They can be used to trigger callbacks when the operation is either completed or failed and can be chained together to create complex asynchronous flows.
Syntax: The following is the syntax for creating a deferred object and resolving it.
let deferred = $.Deferred();
deferred.resolve();
Approach 1: Here, we have an HTML page with a button and a message element. When the user clicks the button, we want to resolve a deferred object and display a message. To achieve this, we first include the jQuery library in the HTML page and then use the $(document).ready() function to ensure that the code will execute when the DOM is fully loaded. Inside the $(document).ready() function, we create a deferred object using the $.Deferred() function. This creates an object that can be resolved at a later time. Next, we bind a click event to the button using the $('#button').click() function. This function will execute when the user clicks the button. Inside the click event handler, we use the deferred.resolve() function to resolve the deferred object. Finally, we bind a done callback function to the deferred object using the deferred.done() function. This function will execute when the deferred object is resolved. Inside the done callback function, we use the $('#message').text() function to update the text of the message element with the string "Deferred object resolved". When the user clicks the button, the click event handler will execute and the deferred object will be resolved. This will trigger the callback function to execute is done, causing the message to be displayed.
Example: In this example, we will see how to resolve a deferred object when the user clicks a button using jQuery.
HTML
<!DOCTYPE html>
<html>
<head>
<script src=
"https://code.jquery.com/jquery-3.6.0.min.js">
</script>
<script>
$(document).ready(function () {
// Create deferred object
let deferred = $.Deferred();
// Bind click event to button
$('#button').click(function () {
// Resolve deferred object
deferred.resolve();
});
// Bind done callback to deferred object
deferred.done(function () {
// Display message when deferred object
// is resolved
$('#message').text(
'Deferred object resolved'
);
});
});
</script>
<style>
body {
margin: 0;
padding: 0;
display: grid;
place-content: center;
background-color: white;
color: black;
}
::selection {
color: white;
background-color: green;
}
button {
border: 2px dotted white;
margin: 20px;
padding: 10px;
width: fit-content;
font: 20px;
}
</style>
</head>
<body>
<h1 style="color: green">
GeeksforGeeks
</h1>
<p>
How to check the lock-state of a
callback list using jQuery?
</p>
<button id="button">Click me</button>
<div id="message"></div>
</body>
</html>
Output:
A Promise object in jQuery is a representation of the result of a deferred operation. It allows you to access the result of a deferred operation once it has been completed, and to attach callbacks to be executed when the operation is completed or fails.
Syntax:
var def = $.Deferred();
var promise = def.promise();
Approach 2: Here, we create a deferred object def using $.Deferred() and a promise object promise using the promise() method of the deferred object. We then use the done() method of the promise object to attach a callback that will be executed when the promise is resolved, and the fail() method to attach a callback that will be executed when the promise is rejected. We also added two buttons with ids "resolve" and "reject" respectively. When the "resolve" button is clicked, the resolve() method of the deferred object is called, which in turn triggers the done() callback attached to the promise object, and shows the resolved data in the div with id "output". And when the "reject" button is clicked, the reject() method of the deferred object is called, which in turn triggers the fail() callback attached to the promise object, and shows the rejected message in the div with id "output".
Example: In this example, we will look at how to resolve a promise object when the user clicks a button using jQuery.
HTML
<!DOCTYPE html>
<html>
<head>
<script src=
"https://code.jquery.com/jquery-3.6.0.min.js">
</script>
<script>
$(document).ready(function () {
let def = $.Deferred();
let promise = def.promise();
promise.done(function (data) {
console.log("Promise resolved with ", data);
$("#output").html("Promise resolved with " + data);
});
promise.fail(function () {
console.log("Promise rejected");
$("#output").html("Promise rejected");
});
$("#resolve").click(function () {
def.resolve("example data");
});
$("#reject").click(function () {
def.reject();
});
});
</script>
<style>
body {
margin: 0;
padding: 0;
display: grid;
place-content: center;
background-color: white;
color: black;
}
::selection {
color: white;
background-color: green;
}
</style>
</head>
<body>
<h1 style="color: green">
GeeksforGeeks
</h1>
<p>
How to use promise object in jQuery? <br>
Click the button below:
</p>
<button id="resolve">Resolve</button> <br>
<button id="reject">Reject</button> <br>
<div id="output"></div>
</body>
</html>
Output:
Deferred and promise objects are both fundamental concepts in jQuery for handling asynchronous operations. While they are closely related, there are a few key differences between them.
Difference between Deferred Object & Promise Object:
Deferred Objects | Promise Objects |
---|
It is used to create and manage asynchronous operations | It is used to access the results of those operations |
It has resolve() and reject() methods for signaling that an operation has completed or failed | It has done(), fail(), always(), and then() methods for attaching callbacks to be executed when the operation is completed or fails. It also has a state() method for checking the current state of the operation |
It is Mutable, meaning that its state can be changed multiple times | It is Immutable, meaning that its state cannot be changed once it is set |
Similar Reads
jQuery Tutorial jQuery is a lightweight JavaScript library that simplifies the HTML DOM manipulating, event handling, and creating dynamic web experiences. The main purpose of jQuery is to simplify the usage of JavaScript on websites. jQuery achieves this by providing concise, single-line methods for complex JavaSc
8 min read
Getting Started with jQuery jQuery is a fast lightweight, and feature-rich JavaScript library that simplifies many common tasks in web development. It was created by John Resign and first released in 2006. It makes it easier to manipulate HTML documents, handle events, create animations, and interact with DOM(Document Object M
4 min read
jQuery Introduction jQuery is an open-source JavaScript library that simplifies the interactions between an HTML/CSS document, or more precisely the Document Object Model (DOM). jQuery simplifies HTML document traversing and manipulation, browser event handling, DOM animations, Ajax interactions, and cross-browser Java
7 min read
jQuery Syntax The jQuery syntax is essential for leveraging its full potential in your web projects. It is used to select elements in HTML and perform actions on those elements.jQuery Syntax$(selector).action()Where - $ - It the the shorthand for jQuery function.(selector) - It defines the HTML element that you w
2 min read
jQuery CDN A Content Delivery Network (CDN) is a system of distributed servers that deliver web content to users based on their geographic location. Including the jQuery CDN in your project can improve the performance, enhance reliability, and simplify maintenance.What is a jQuery CDN?A jQuery CDN is a service
4 min read
jQuery Selectors
JQuery SelectorsWhat is a jQuery Selector?jQuery selectors are functions that allow you to target and select HTML elements in the DOM based on element names, IDs, classes, attributes, and more, facilitating manipulation and interaction. Syntax: $(" ")Note: jQuery selector starts with the dollar sign $, and you encl
5 min read
jQuery * SelectorThe jQuery * selector selects all the elements in the document, including HTML, body, and head. If the * selector is used together with another element then it selects all child elements within the element used. Syntax: $("*")Parameters: *: This parameter is used to select all elements.Example 1: Se
1 min read
jQuery #id SelectorjQuery 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. Elaborating on the terms, it simplifies HTML document traversing and manipulation, browser event handling, DOM animations, Aja
1 min read
jQuery .class SelectorThe jQuery .class selector specifies the class for an element to be selected. It should not begin with a number. It gives styling to several HTML elements. Syntax: $(".class") Parameter: class: This parameter is required to specify the class of the elements to be selected.Example 1: In this example,
1 min read
jQuery Events
jQuery Effects
jQuery HTML/CSS
jQuery Traversing