Creating a custom promise in jQuery
jQuery. But, for a recap, let’s first see a situation and then we will see how to resolve this using a custom promise.
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.
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.
Let’s see the output
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.
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.
Since we are resolving the promise, the successCallback will be executed. We have passed the successCallback to the then method of the promise.
If we want to pass some value to the then function, we can do that when we resolve. For eg.
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.
This is the final output
In the next post, we will learn how to create custom promise in AngularJS.
Till then, Happy Learning.