1

Create a Custom Promise in jQuery

[Social9_Share type="horizontal"]

Creating a custom promise in jQuery

In the last post, we understood why we need a promise and What are promises in javascript?. In this post, we will see how to create a custom promise in jQuery. But, for a recap, let’s first see a situation and then we will see how to resolve this using a custom promise.

jquery code

Here, I am making an asynchronous call(action that completes at a later time) inside the function doSomeAsyncAction. I want the console log “to be happened after the timeout callback” to be executed only after the setTimeout function is completed.

If you execute the above code, you will get the following output in console.

jq_promise2

This is not what I wanted. I want the next line to wait till the setTimeout function is completed. How to solve this issue? In this scenario, let’s use custom promise of jQuery.

Let me rewrite the above code with custom promise.

jquery code with promise

Let’s see the output

modified output in console

You can see that, now the order of execution is correct.

How did we do that? Let’s break the code and understand.

To create a custom promise, first we have to create a Deferred object. This is the object which creates a promise and also decides whether the promise should be resolved or rejected.

var defer = $.Deferred();

This creates a new Deferred object and assigns to a variable 'defer'.At the end of the function, you can see that we are returning the promise object of the Deferred object.

return defer.promise();

As we learned in the earlier post, each promise will have a then method which accepts two parameters, a successCallback and an errorCallback. If the Deferred object resolves, the successCallback will be executed and if the Deferred object rejects, the errorCallback function will be executed.

We are resolving within the setTimeout callback.

jq_promise5

Since we are resolving the promise, the successCallback will be executed. We have passed the successCallback to the then method of the promise.

jq_promise6

If we want to pass some value to the then function, we can do that when we resolve. For eg.

jq_promise7

In this scenario, we are passing an object to the resolve method and that object will be available in the successCallback function as an argument.

jq_promise8

This is the final output

jq_promise9

Thats all.
In the next post, we will learn how to create custom promise in AngularJS.
Till then, Happy Learning.

Post a comment