[NEW] Provenance and Attribution: Minimize IP liability for GenAI output
Home / Blog /
How to Use jQuery Promise with JavaScript
//

How to Use jQuery Promise with JavaScript

//
Tabnine Team /
3 minutes /
October 6, 2020

jQuery is a feature-rich JavaScript library.

It is designed to simplify multiple areas of JavaScript development, including:

  • DOM manipulation
  • Event-based interaction
  • Animations
  • Ajax
  • And more!

jQuery’s promise() method is used mainly with jQuery animations.

jQuery promise was released in mid-2011 as part of JQuery version 1.6. At the time, the definition provided was: “Return a Promise object to observe when all actions of a certain type bound to the collection, queued or not, have finished. jQuery objects can now return a Promise to observe when all animations on a collection have completed.”

jQuery provides several methods that support custom animations (for example, the animate(), fadeIn(), and slideUp() methods). Their return value is the jQuery object.

Every jQuery animation method accepts a callback function as the last parameter (named ‘complete’ by the jQuery documentation). This function will be called once the animation has ended. You can build on this foundation using promise() instead – this leads to much more readable code.

Syntax

The syntax of jQuery’s promise method is as follows:

.promise(type, target)

The parameters to this function are:

  • type – the type of event queue which needs to be observed. The default is fx, which refers to animations.
  • target – the object onto which the promise methods have to be attached. When provided, the methods will be attached onto the object, returning this object rather than creating a new one.

This method returns a promise which will be automatically resolved when all actions of the specified type that have been bound to the collection (whether queued or not) have completed.

Basic example

The following example performs some basic animations, using the promise() method to await their completion:

JavaScript

$('button').on('click', function () {
  $('h2').each(function (i) {
    $(this).slideUp((i + 1) * 2000)
  })
  $('h2').promise().done(() => {
    $('h3').text('The end...')
  })
});

HTML

<button>Credits</button>
<section class="credits">
  <h2>Starring: John Doe</h2>
  <h2>Director: Shila Randell</h2>
  <h2>Producer: Mark Grey</h2>
  <h3></h3>
</section>

In the example above, clicking the button initiates a function that will cause the <h2> tags to slide up in the browser window. This is a standard jQuery animation. Instead of using a callback function at the end of the method called, there is a new method – promise() – applied to the same element group (i.e. the collection). When all animation actions have completed, the done() method will be called. The done() method adds text to the <h3> element: ‘The end’. This will occur only after all of the <h2>-based credits have completed sliding upwards.

Note: if there is no active animation on the collection, the promise will be resolved immediately. The following example demonstrates this:

JavaScript

const myPromise = $('h1');
myPromise.promise().done(() => {
  console.log('Promise resolved');
  //expected output: Promise resolved
});

HTML

<h1>I promise</h1>

In the example above, ‘Promise resolved’ will immediately be printed to the console.

jQuery promise using when()

You can also manage jQuery promises using the when() method, as seen in the following example:

JavaScript

const togglePsw = function () {
  return $("div").fadeIn().delay(2000).fadeOut();
};
 
$("button").on("click", function () {
  $('h3').text("Your password is:");
  $.when(togglePsw()).done(function () {
    $('h3').text('Have a nice day!');
  });
});

HTML

<button>Show Password</button>
<section>
  <h3></h3>
  <div>sjhf68</div>
</section>

In the example above, clicking the button initiates a function that adds “Your password is:” to the <h3> element. At the same time, when() is activated, calling the togglePsw() function. The togglePsw() function activates jQuery animations (fadeIn(), delay() and fadeout() methods). The code will only continue to the next phase once all of these functions have completed, changing the text of the <h3> element to “Have a nice day!

 

Related Articles:

JavaScript – How to Use Asynchronous Functions

JavaScript – How to Change the Background Color

JavaScript – How to Use Cookies