This .promise() method in JQuery Returns a Promise object to be observed when certain type actions bounded to the collection, queued or not, are ended.
Syntax:
.promise([type][, target])
- type: This parameter specifies the type of queue which needed to be observed.
- target: This parameter specifies Object onto which the promise methods need to be attached.
Parameters:
Return Value: This method returns a dynamically generated Promise which is resolved once actions bounded to the collection, queued or not, have finished.
There are two examples discussed below:
- Example: In this example, the Deferred() is used to create a new object and after that then() method is called with notify and resolve method.
<!DOCTYPE HTML>Â
<
html
>Â Â
<
head
>
   Â
<
title
>Â
     Â
JQuery.when() method
   Â
</
title
>
 Â
</
script
>Â
</
head
>Â Â Â
<
body
style
=
"text-align:center;"
>
   Â
<
h1
style
=
"color:green"
>Â Â
       Â
GeeksForGeeks Â
   Â
</
h1
>Â
   Â
<
p
id
=
"GFG_UP"
>Â
   Â
</
p
>
   Â
<
button
onclick
=
"Geeks();"
>
   Â
click here
   Â
</
button
>
   Â
<
p
id
=
"GFG_DOWN"
>Â
   Â
</
p
>
   Â
<
script
>Â
       Â
var el_up = document.getElementById("GFG_UP");
       Â
el_up.innerHTML = "JQuery.when() method";
       Â
var def = $.Deferred();
       Â
function Geeks() {
           Â
$.when().then(function(a) {
             Â
alert( "when() method called this alert()." );
           Â
});
       Â
}Â
    Â
</
script
>Â
</
body
>Â Â Â
</
html
>Â Â Â Â Â Â Â Â
Output:
Before clicking on button:
After clicking on button:
- Example: In this example, the Deferred() method is used and the state of Deferred object is checked.
<!DOCTYPE HTML>Â
<
html
>Â Â
<
head
>
   Â
<
title
>Â
     Â
JQuery.when() method
   Â
</
title
>
</
script
>Â
</
head
>Â Â Â
<
body
style
=
"text-align:center;"
>
   Â
<
h1
style
=
"color:green"
>Â Â
       Â
GeeksForGeeks Â
   Â
</
h1
>Â
   Â
<
p
id
=
"GFG_UP"
>Â
   Â
</
p
>
   Â
<
button
onclick
=
"Geeks();"
>
   Â
click here
   Â
</
button
>
   Â
<
p
id
=
"GFG_DOWN"
>Â
   Â
</
p
>
   Â
<
script
>
       Â
var el_up = document.getElementById("GFG_UP");
       Â
el_up.innerHTML = "JQuery.when() method";
       Â
var def = $.Deferred();
       Â
function Geeks() {
           Â
$.when(def).done(function (x) {
             Â
$('#GFG_DOWN').append('when() method is executed.')
           Â
});
           Â
def.resolve();
       Â
}Â
    Â
</
script
>Â
</
body
>Â Â Â
</
html
>Â Â Â Â Â Â Â Â Â Â Â Â Â Â
Output: