2Hats . 2 minutes

jQuery deferred object and promises

 

Deferred is a concept that can be hard to understand at first, but once you get a hold of it, it is extremely powerful and simple to use, just like any other jQuery function. So, I will try to explain it using an example and try to explain the concept first to see why we would use them at all.

You have 10 ajax requests going on in a page and you need to trigger an alert after all of them are completed. There is no guarantee that they will be finished in order. Some may take a lot of time to execute while some may be fast. You have no trigger for this. This is where promises come into play. To put it simply, it is just an object which we can manipulate to trigger the completion of one or many asynchronous events (like ajax requests).

A promise is a subset of the deferred object. You can change the state only for a promise.

This is how you create a new deferred object

As you can see from the above example, when you create a new deferred object, it will be in a state ‘pending’. Then you can either reject or resolve it whenever you want. You can check the state of the promise to trigger other callback functions,

$.done() , $.fail()

Let’s try another example. You have 3 inline block div elements on the page, 100px with and height. You want to fade each of them one after the other and trigger an alert after they are done.

We already discussed the promise trigger callback functions like $.done()  on “resolve()” and $.fail() on “reject()”, there is another callback function called $.always() . This doesn’t care whether the promise is passed or failed, it works in either conditions.

def.always(function(){

alert(“DONE”);

});

There is a another callback function $.then(). This simply running the deferred and it execute the done callback and then fail callback.

def.then(

function(){

alert(“Done”);

},

function(){

alert(“Fail”);

}

);

We can also use another method called $.when() . This can stack multiple synchronous operations. For example, when you want to run a function after completing some other functions,  then you can use this method. This fires $.done()  only  after  finished those functions.

Example:

blog
Greetings! I'm Aneesh Sreedharan, CEO of 2Hats Logic Solutions. At 2Hats Logic Solutions, we are dedicated to providing technical expertise and resolving your concerns in the world of technology. Our blog page serves as a resource where we share insights and experiences, offering valuable perspectives on your queries.
Aneesh ceo
Aneesh Sreedharan
Founder & CEO, 2Hats Logic Solutions
Subscribe to our Newsletter
Aneesh ceo

    Stay In The Loop!

    Subscribe to our newsletter and learn about the latest digital trends.