Promises š¤ in JavaScript š»
A beginnerās guide to awesomeness!
What is a Promise?
To put it in plain simple words, it is a contract between the promisee and the promiser. It says that the promiser will always send something back to the promisee (you), it can either be a good š or a bad gift š„.
What is the structure of a Promise?
A promise has the following structure,
It is a JavaScript object which either resolves (you will get a good gift) or rejects your task (you will get a bad gift). Whenever you want to return an object from a promise, it is passed as a parameter to either the resolve()
or the reject()
function.
How to use a Promise?
Letās say that you want to request a gift, here is how you do it,
If the promise calls the resolve()
function, we go into the then
block and if it calls the reject()
function, we go into the catch
block. Hence, it is ensured that we will always receive a response. Notice that the then
and catch
blocks need to be applied on a Promise object.
How do I wait for a Promise?
In the previous example, we donāt really wait for the gift to arrive, but rather just mention what needs to be done after we get the gift. But what if I am really excited about receiving the gift and want to wait until it arrives?
Hereās how to do it. You use the async
and await
keywords!
We are not using async
yet, but donāt worry, read on ā¦
How do I wait for Promises one after another?
OK, so you got your gift and found out it was an iPhone 12, wow! Now you are feeling optimistic and want to request another gift. Letās say that you want to request another gift only if the first one was good (i.e. successful).
Since we want every Promise request to be unique, letās create a function that creates a Promise for us!
Now letās see how you can request another iPhone 12 if you get an iPhone 12 the first time, hehe š¤! (notice the async
and await
usage)
All thatās great, but you can see that we repeated the code for handling a bad gift. Code repetition is never a good programming practice! Hereās what you can do instead!
Woah! Where are the then
and catch
blocks for the second Promise š¤?
Donāt worry, they are right there in front of you! So, in the then
block of a promise, you can request another Promise, but remember that a then
and a catch
can only be attached to a Promise object, so we need to return this new Promise object to handle it down the line. This can be seen in line number 8.
So whenever you see a resolve(obj_good)
call, it passes the obj_good
object to the very next then
block down the line. Similarly whenever you see a reject(obj_bad)
it passes the obj_bad
object to the very next catch
block.
So we just add a new then
after the first one to handle the second Promise. And the catch
block beautifully handles the very first bad gift.
Remember, that a catch
can never be followed by a then
block. And having multiple catch
blocks with the same signature one after the other will be redundant since the very first one will handle all the bad gifts. Great š, we are almost done!
Wow, that looks beautiful! And yup, you guessed it! You can now request more gifts sequentially, like so,
So you have now dealt with the following issues simultaneously,
- You have prevented code repetition.
- You have prevented code nesting.
- You have handled a success-chain beautifully!
By a success-chain, I mean that you want to execute a sequence of tasks T1, T2, T3, ā¦ in such a way that you go to T(n+1) only if T(n) is successful.
How does this translate to my application?
The answer is quite simple, a good gift means that your task was successful and a bad gift means that your task failed. The task can be literally anything, synchronous or asynchronous!
Here is an example, you want to build a website with a login functionality where,
- T1: User logs in successfully
- T2: User obtains the list of items he/she can purchase
You want to go to T2 only if T1 is successful!
Try it out yourself!
Click on the attached JS Fiddle URL. Make sure that you choose the āClear console on runā option and then click the Run button! Click the Run button multiple times to try out your luck! Here is a demo GIF.
Ending note
I hope that you enjoyed this post! You now have a basic understanding of how Promises work. Remember, Promises are the future of JavaScript!