Promise in JavaScript | Part 1: Consuming a Promise
Understanding JavaScript();
in this practical world promises are never meant to be kept 💔, but this is not the same in JavaScript.
relax, nobody ditched me because I never tried 😅, also nobody approached, and I don’t know why 😅.
For the time being, promises are a hot topic that everyone uses, and many of us tried to understand it but, it is a bit tricky thing to understand, and some of us are still trying to understand it.
let’s try to understand what is a promise in simple words(English)
Here’s what Google says about promise: to say definitely that you will do or not do something or that something will happen.
ya ya, I know “Kuch 🔔 bhi smj nai aya” (understood nothing), ok without wasting a bit, let's dive deep into the story of promise in the world of javascript.
in this story, we will cover what a promise in javascript is, why it is used and how to consume a promise, “In Simple Terms”.
we can create and consume the promises, in this part of the story, we will be looking at consuming a promise.
Things to remember:
- javascript executes asynchronously 🔀.
- and javascript waits for no one(it doesn’t wait for the previous piece of code to get executed, before executing the next line of the code).
What is a promise?
explaining simply, a promise is “A reserved space which will be filled by the value in future”.
for example, you are sending your friend to buy an X product from the market and you don’t know when he/she will return and will they bring that product. so you reserve a place for the product your friend may bring whenever he/she returns.
if we look at the above example programmatically, the promise is a reserved space where the result of the task/operation will be stored, and we don’t know how much time that task/operation needs to get completed.
according to MDN Docs, a javascript promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
- eventual completion: we don’t know when it will get completed.
- asynchronous operation: operations that are triggered in parallel.
- resulting value: output of the operation.
code example on how you can consume the promise.
- the above code snippet is fetching some data from some API using the fetch method in javascript.
- this returns us a promise object with pending status, check the console output in the example below.
- you might think why there are different states in the output of the same promise, don’t get confused with the state because the first line Promise{<pending>} displays the state when the promise was logged, and line 3 [[PromiseState]]: “fulfilled” is the state displayed when promise gets resolved.
- here we don’t know how much time it will take to fetch the data from the API, it reserves some space for the result/rejection that will be returned.
Promise has 3 states in total, Pending, Fulfilled and Rejected.
- when any promise is made it will be in a Pending state, this is the first stage of any promise made. This state means the execution of the task/operation is in process and it is waiting for the data.
- the state is changed to Fulfilled when the promise gets resolved, it means the object is filled with the data that the promise was expecting from the function to be returned, basically when the task is successfully completed.
- and the promise shows the Rejected state when some error or issue with the task/operation that the promise was expecting to be finished successfully.
the output of the task/operation will be in the last key i.e. Response, if you directly print the response of promise it will be the promise object [refer promise response image].
and most importantly, the promise object is immutable, nobody can tweak the response.
Why a promise is used?
you might be thinking just to fetch the data from any API do we need a promise? seriously? 😕
I can use a timeout for the same, right? my counterargument will be how much time will you wait? is it fixed every time?
Ummm 🤔, then we can use the callback function in javascript, yeah we can use it but if you have read the last story by me Callback Function in Javascript you might know there are some drawbacks of callback functions, i.e. inversion of control, it can be resolved using promise 😃.
What is an inversion of control? here’s some idea about the concept of inversion of control. We pass the function to the parent function as a callback function, once the parent function execution is completed the callback will get executed, and we now don’t have any control over the function that is passed as a callback function, whether it will get executed or not, how many times it will get executed, what happens if the parent function had some error in it, or what if the parent function is written by an intern(just kidding) 😅, there are N possibilities.
we will be continuing the example that we used in Callback Function in Javascript, i.e. fetch user, on basis of the user data fetch the details of the friends of that user, get the address of those friends, and send the new year gifts to those friends and surprise them(i like surprises as well 🎅).
this is how it can be written with callbacks
but, unfortunately, now I am aware of promises, sorry callback functions.
I used setTimeout functions to mimic the API call.
- writing it with the promise is a much cleaner way of implementing the above scenario.
- you can chain the promises using a .then() method provided by a promise API, after fetching the userData, a callback is called and we will fetch the user friends and it will return a promise again, and so on.
- here you have complete control over the code, and it guarantees a call to a callback function.
- it gives you a clean code structure, and the code will grow vertically instead of growing horizontally(it prevents code from being a pyramid of doom), and it will be much more readable.
- also using promises provides you with better error handling, you can use the .catch() method of promise API to handle the error.
you might be thinking we are using callbacks here as well then what is the difference between directly using the callback functions and not using the promise? 🤔
so let's understand why Promise and why not Callback. 😎
- with promises, we attach a callback function, whereas in the callback function we pass a function as a callback
- attaching callback function provides you with control over the code, whereas you don’t have control over the code when you pass a callback function as a function parameter.
How to consume a promise?
Note: we will cover “how to create a promise” in the next part of the story, as this story is getting stretched.
here we have an API endpoint which fetches the user, we don't know how much time the endpoint will need to get the user, and also we know that the javascript executes asynchronously, it waits for no one.
we will fulfil the above scenario using the promise
- first, we are fetching the user. It will return the promise (output attached below).
- we need to attach a callback function to the promise object so that we can access the response from it, we need to convert it to JSON, which again returns a promise.
- attaching a callback function to the JSONified response will get us the data of the API call(check the above code snippet).
and ya that's it, you have learned a lot about promises.
Hope you enjoyed the story 🤗 but just enjoying is not enough give it a try, and let me know if you have any doubts around.
grab a coffee ☕️ and stay tuned for part 2 which covers how to create a promise and much more.