Promises | Ep 02 Season 02 - Namaste JavaScript

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
promises yes so promise is the most important topic you should know if you are a JavaScript developer if you are giving a front-end interview then definitely 100 percent there will be questions around promises knowing promises will not just help you in your interviews but will also help you become a better JavaScript developer while you are doing your day-to-day coding see I can tell you what promises are in just 5 to 10 minutes but no I won't do that in this video we will be diving deep into promises just like how we do right and we will explore the beauty of promises we'll see how beautiful promises are so that's why this episode can go a little long but I promise that you will fall in love with promises after watching this video so I just please request your attention and just keep watching this episode of Namaste JavaScript season 2. so now listen to me very carefully promises are used to handle async operations in JavaScript now I will take a code example and will show you how things used to work before promises and then how it used to work after promises let's just begin let's dive into the code now so I will take a take an example suppose we are creating an e-commerce website like Amazon right so we have cart in it suppose we have a cart in it let's call it as const cart right so this cart is nothing but an array for the sake of Simplicity I will just use strings over here okay and let's add some items to the cart what item should we add let's add shoes and tell me some products okay let's add pants let's add kurta to it why not right so let's add kurta right so this is our card every e-commerce website has a card along with the card suppose we have two more apis let's call them as create order API right this API takes cut to it right takes the cart items and will return us the order details or an order ID right what this will do is this will create an order in our database or whatever it will do and will give us an order ID it will create a order right and then there is one more API let us call that as proceed to payment right this API basically proceed to payment okay this API will then take this order ID and will take you to the payment page or this will proceed to payment right this so now what will happen is these two apis are asynchronous create authorization as proceed to payment is as impressed we don't know how much time it will take right and they are dependent on each other right so we can only do proceed to payment once we have created the order make sense right so how so now let us see that how we used to write this code using callbacks right call back seems to be very crucial part when writing a synchronous code in our programming so how we handle this type of situation in our code using callbacks is that we wrap this function inside a callback function right this proceed to payment we will wrap it inside a callback function and what we used to do is we design our apis in such a way that we pass this callback function let us just grab this and we'll pass this fallback function to create order API right this this used to be the case now it is the responsibility of create order API to create an order first of all and then we'll call our callback function back once the order is created with the order ID so this is how we used to handle async operations using callbacks but my dear friends there is a very important issue with this code what is that issue if you have seen my previous video you would have guessed it already yes that issue is inversion of control so what does that mean is that we have given this callback function we have passed this callback function to create order API and now we are just sitting back relax as a developer that at some point of time this create order function will just call our callback function back and everything will be peaceful part part what if what if we are just blindly trusting this create order API and it never calls our callback function back or it might call it toys who knows because this create order API can be in some other service can be in some external world can be written by some other developer or some other team or some intern and we can't just blindly trust these apis isn't it so what I mean to say is that we have given the responsibility of our code proceed to payment to some other API and it's not in our control anymore we have just passed in and we are just expecting it to be like randomly magically being called after the order is created isn't it risky so passing callback functions like this isn't reliable we are just giving the control of our program to some other part of our code which we are not aware of isn't it this is not a very confident way of writing code so how we can solve this so now let us just see that how we can handle this type of situation using promises okay so what will happen is if we were designing these apis so we would have designed our create order API in such a way that whenever we this API right create order API will no longer take a callback function it won't take a callback function but it will just take card details right and what it will do is it will return us a promise what is a promise I will tell you so we will capture that promise into a variable let us call it as promise right so whenever you call this line right whenever this line is executed by JavaScript this create order API will return us a promise and promise is nothing but you can assume it to be an empty object right empty object with some data value in it right and this data value will hold whatever this create order API will return to us right so now listen to me very carefully this create order API is an async operation it will take some time to execute but we don't know how much time it will take this create order API might take five seconds six seconds or we don't know how much time it will take but as soon as this line is executed it will return us an object right it will return us an object with a data with some empty undefined property right undefined or an empty value right what does undefined means an empty value it will just assume that it is returning as an empty object with some property data and it is undefined not defined at that moment itself and suppose after five seconds six second 10 seconds whenever how much ever time it takes what it will do is it will create an order and will give us order details and will fill this object back at some later point of time got it I will repeat it once again listen to me very carefully because this is very important whenever JavaScript engine will execute this line right so this create order API will return us a promise promise is nothing but an empty object over here and what will happen is the program will just go on executing suppose if there are more lines of code over here they will start a they will start executing and after five seconds six second or how much ever time it takes what will happen is This Promise object this empty object will be filled with data automatically Right This Promise object will fill this data automatically and we will have order details in it after whatever async time it takes got it this is what promise is so now you can ask me a very important question that what will happen once we have this order details once we have this data with us how do we continue our program what will happen to proceed to payment yes I will tell you what happens so what we will do is now we will attach a callback function to This Promise object right and how do we do that I'll show you so we will use a function dot 10. this is the this is a function which is available over promise object this is the promise object we can use promise object right whatever we call it as we will use promise dot then and we will attach a callback function using this then function okay we will have this callback function that we used to pass in earlier and we will attach it to our promise object now what will happen is wherever right earlier this data used to be undefined right this was empty as soon as JavaScript engine executed this line this was undefined this was empty but after certain point of time this will be filled with exact data that will be returned by create order API right here we will have order details right and once we have data inside This Promise object what will happen is this callback function that we attach to This Promise object will be automatically called right so this is how we use we write code in world of promise and this is how we used to do earlier right so now I know that you might have a lot of doubts in your mind that Akshay what are you smoking this is looking more complicated than callbacks right the earlier solution how did how did use help us right we are still using callbacks over here right so what what Improvement did we make in our code I will tell you my dear friends this piece of code is a lot lot better than this piece of code how can you guess I will tell you listen to me very carefully what we did in the earlier solution was we passed this function to create order API and we were blindly trusting create order API we were relying on it and in this case we are attaching a callback function to a promise object there is a difference first one we were passing this callback function to another function right and here we are attaching a callback function to a promise object there is a difference between these words passing a function and attaching a function so what happens in this case is we just pass this function and now create order API would have called it whenever it wants to right and in this case we will have the control of our program with us right how that create order API will only do its job it will create an order and it will it will fill the promise object with the data the order ID wherever it wants to and as soon as this promise object it filled with that data it will automatically call our callback function back and we will have the control of our program with us promises gives us this trust and Promises gives us this guarantee that it will call this callback function Whenever there is data inside the promise object and in the earlier piece of code we had a lot of doubts right that what if this create order API might call our function twice or Thrice or it might never call it promises handles it beautifully what will happen is as soon as we have data inside promise it will call this function definitely hundred percent of the time that is the guarantee given by JavaScript right and it will call it just once and only once and we will also have control of our program with us as we are not passing our code to some other external function isn't it beautiful to have this guarantee and Surety as a developer it's beautiful my dear friends so I told you that okay promise object is an empty object with some data field or something no it is much more special and it is much more advanced than that okay now I will show you the real promise object we will we are diving deep now okay we will just exactly see how promise objects looks like just let me write some code to show you that okay so if you uh if you want to see that object we will use a function fetch if you are writing JavaScript code then you would have already been familiar with this fetch function it is a basically an API given by browsers to us to make external calls so now we will use this fetch function to make an API call to GitHub servers and will get a user info with us so this open source API gives us the info of this username I have written down my GitHub username over here so I'm just taking this as an example so what we will do is we will try to fetch this user info from this API okay and by Design This fetch function right this fetch function returns us a promise just like I was telling in create order API right here so this fetch function will return us a promise and let us just capture that promise into a object which is known as user okay and we will pass this GitHub API over here now my dear friends what will happen is as soon as this line of code is executed we will get a promise object inside this user okay so fetch returns us a promise okay and let us see it dive deep into the console and what we will do is let us just go to sources let me just add a debugger over here so I have added a debugger before this line is executed now as you can see user is right now undefined but you will slowly see as soon as this line is executed you know this line number 15 what will happen is as soon as this fetch function will be called a promise object is going to be returned inside a user object and let us now see how does that promise object looks like let me just run it yes see now this is the promise object my dear friend are you able to see this let me just zoom a little bit here and just oh my God I not able to show you let me just yes so this is a promise object over here right this is an empty object that I was showing you over here and let us just see what is inside This Promise object so we have a prototype over here and we have promised it and we have promise result and whatever I was telling you that empty object and the data is equals to undefined it is this right so right now this promise is in a pending state so what are the state of a promise I will tell you there are two things one is the state of a promise and one is the result so result will store whatever data it returns right whatever the data that fetch method will return this will be stored inside promise result and promise State tells you that in what state that promises initially the promise will be in pending State and once we have got the data back remember I was telling you that it might take four seconds five seconds for that osynchronous operation to get completed so after that that promise State changes to fulfilled State now I'll show you something really interesting okay so let's move to the console and over here suppose if I have read writing console.log of user let's just print user so before I run this code just can you guess what this console log user will do so what will happen when JavaScript runs this code is it will just have this will this is a normal code right and once this line 15 is executed fetch will return as a promise like user promise and this console log will log that promise so what do you think at this point of time on line number 17 the state and the result of Promise will be remember this is an async operation it takes some time to execute what will it log here pending or fulfilled I interesting question right let us just see so my dear friends it is logging pending and if I expand it so it shows you fulfilled you know it took me like five days and like six Red Bulls to find out that why is this pending and this is fulfilled you know this is this inconsistency is just in Chrome browser don't worry is is a part of Chrome browser but it generally I'll tell you I'll explain you why it is behaving in this way so actually what happens is when this console log statement is executed at this point of time the user the promise object is in a pending State okay how because JavaScript engine executes JavaScript engine does not wait for anything it just quickly execute whatever is there right so it just executes line number 13 then 15 then 17. inline number 15 fetch returns a promise and that promise at that particular time is in a pending state it takes some time to get the data and fill it back right to get fulfilled but JavaScript does not wait for that right it just goes on and prints console log into the console and that's why this promise is pending over here but what does Google Chrome does is after some point of time right after eventually this data will come into this promise object so if you expand it it shows you the current state of the promise so that's why this is fulfilled right now but when it was logged it was in pending state so that's why this inconsistency but assume okay but right now at this point of time the promise has been fulfilled and as I told you that this result right promise result which was undefined earlier I showed you over here right using a debugger so which was undefined is now filled with our response and if I open that we have body we have headers we have a lot more things over here so that data is inside this body this is a readable stream right so we can't just see a readable stream like this right but it is there there is a way to extract it we can convert this readable stream into a Json and extract it but what I want to tell you is that promise right now isn't fulfilled it this is how a fulfilled promise looks like earlier it was in pending and after the tracing operation is done it just fulfills it now what if what if what if we had some callback attached to this promise object right how do we attach it I assure you right then and we had a function a callback function over here and what we can do is here right if we have this data so this data we can this data the result over here this data will come over here and we can just use this right we can just use this as we want to we can just do whatever we want to with this data and that's how we attach callbacks to promise so whatever needs to be done after we have data inside our user object that needs to go in like this so if I save this so we get this response over here this data right and we can use this in our program we can do whatever we want to with this data so that's how we generally handle promises so let us just get back so this is how my friends a promise objects looks like and this is a spatial object in JavaScript so this special promise object brings a lot of trust in this transaction because JavaScript guarantees that this promise object can only be resolved once either it will be success or a failure over here it is fulfilled it can be rejected also okay and the state can be only three inside a promise there can be only three states one is pending one is fulfilled and one is rejected if we go to the mdn.com documentation let us just see see there can be only three states inside the promise one is pending fulfilled and rejected that's all three states it can have right so this brings us a lot of trust in the transaction and one more important thing is that promise objects are immutable what does that mean so whenever it is fulfilled and whenever we have data inside our promise object we can just pass it here and there in our code and we don't have to worry about that someone can mutate that data so if you would want to do a user dot data dot something equal to something you can't just edit this user now right this is so so so great as a developer right because you have control over this object Right This Promise data and there is a way to attach handlers to it using then right so that's how we do that and nobody can mutate it it's immutable immutable and dissolved just once and you can pass in wherever you want to such a beautiful thing isn't it so now my dear friend let us talk about interviews right the most interesting part how do you answer question in your interviews for that let me just get rid of this right I will tell you so what if your interviewer tells you that what is promise what is a promise in JavaScript how do you answer that question what is this promise how would you answer that I'll tell you just listen to me very carefully there are a lot of different definitions of promises running all across the internet okay so some people call This Promise object as a placeholder right placeholder which will be filled later with a value make sense promise object is a placeholder for a certain period of time until we receive a value from a asynchronous operation isn't it so there is this is one definition the other definition some people would like to call it as a container for a free future value some people use the word future value for this value which it will have after the promises resolved right so it's a container for a future value some people like to call it like that and there is one more definition of promises over mdn documentation which I personally like now but first time when I read it right my I got a headache while I was trying to understand what does it trying to say by this line right but now I find that this is the most beautiful definition of promises let us just try to understand this and now when I have explained you a lot right so this will make sense to you now so promise is an object representing eventual completion of an asynchronous operation sounds complicated right but no it is not I tell you so This Promise over here is an object that represents an eventual completion of an asynchronous event okay sounds complicated let me break it down to you promise is an object that you can remember represents the eventual completion of an asynchronous operation because see this is an asynchronous operation create order and it will eventually be completed so promise is an object representing eventual completion of an async operation just try to remember it once again promise is an object representing eventual completion of an async operation eventual completion right eventually completed and async operation that's how mdn defines promises to be I find that definition more Technical and more precise and more beautiful for the interviews because sometimes if you just say that container over a future value then you would have to back your answer with a lot of explanation but if you will say to your interviewer that promise is an object that represents an eventual completion of an async operation I dare you he won't ask you anything except this if our promises he would know that you know promises already okay so that's how try to remember it it's very easy once again promise is an object which represents the eventual completion of an async operation eventual completion of async operation async Operation right eventual completion async operation as it is an object easier I know that this video is getting a little longer but please give me 5-10 more minutes I want to explain just one more Topic in this video and then in the next video rest of the things okay so let me just close my browser let's get back to code again now listen to me very carefully this is the last part of the whole explanation which I wanted to give okay so what will happen is we solved inversion of control which was a major issue while using callbacks right we were giving control of our code to something else but there is one more issue with callbacks right if you have seen my previous video you would know that there was an issue of callback hell I'll just quickly explain you what it is right now if you haven't watched my video though watch that video also but I'll quickly explain it over here also so suppose in an e-commerce website what we do is we create an order then we have a proceed to payment then we have an API suppose we have an API for show order summary right once the payment is done we show an order summary right which takes payment info and there is one more API suppose update wallet update Wallet balance wallet wallet uh balance right so once the order summary is shown so just update the Wallet balance okay so it just update the Wallet balance okay so now how do we and these are dependent on each other okay once we do create order then we do proceed to payment then we do show order summary then we do and then we update the wallet right it happens in a sequence so what will happen is how do we use to write this type of code in our old fashioned right the Callback way so we used to have a callback which have this show order summary and we used to pass this call back right this callback method we used to pass this callback method into our proceed to payment remember this is how we wrote code let me just make it a little more readable to you okay and what will happen is now if you see clearly we have our create order then proceed to payment then show order summary and once the order summary is shown then we will do update balance so we have another callback and when we write this type of code when we have a lot of apis which depend on each other so we tend to fall into a callback hell this is known as callback help now our code starts to grow horizontally instead of vertically isn't it this is also known as Pyramid of Doom and it takes and if suppose we have more if and else cases more nested callbacks then this code becomes very ugly and hard to maintain you don't know how and where what API is being ending right so this we want to avoid promises helps us avoid this as well and this is handled using promise chaining so promise comes with an important feature of Promise training yes that term sounds very complicated but it is not I'll show you that how we can write this type of code using promises if suppose these apis were returning as promises how do we handle this type of situation okay so this is the way of writing promises so if you see it clearly then this create order API was returning as a promise and then we were attaching a callback function to this create order apis returned promise so this is a way to do that or we could have just instead of doing promise dot then we could have just did we can just do a DOT then after this create order API so this is same right so it is equivalent to writing this right so this create order API will return as a promise and then we will attach a callback function over here right so this is same as getting a variable and then attaching then to it or we can just simply write like this using promises right so suppose if after proceed to payment we also had to show order summary so what we you we so what we could have done is we could have just added one more then statement after this right and we would have just attached another callback function to This Promise chain right this is known as promise chaining and we would have just done show order summary over here and instead of payment info let's just add payment info over here so that's all that's how we would have handled it inside our promise world right and what if there was a plate update Wallet balance also so we would have asked added one more callback we've to this chain right and we would have done update wallet over here right let me just show it to you so our code would have become Lean by writing like this so one more important thing to note over here is that a lot of developers fall into that that issue right there is a bug in a lot of code right you would pull your hairs if you will fall in that bug is that whenever you are attaching a lot of then then function and lot of callbacks in This Promise chain what happens is we used to pipe the data right we want this data to flow in the whole chain what will happen is whatever is the response of this create order should pass into this this chain and then whatever the whatever is the response of this prior C2 payment should pass down the chain and then whatever is there returned from show order somebody should pass down the chain for that you have to take care in mind that you return from here okay so we always return a promise from in promise when we are chaining it right so that's when we will get data properly into our chain and a lot of times we as developer forget to write this right so just make sure that you are doing this when you are handling it so this is how we write code and our code does not grow horizontally but it is in a meaningful chained fashion okay so this is how we write this piece of code inside promises and one more thing some some developers also prefer to use Arrow functions over here right that makes it a little more lean uh I I don't want to question about readability but the code will look something like this if you will have Arrow functions over here we can just get rid of return statement so some some developers find it much more readable like this okay so they kind of just remove all these returns and all right because there is just one line over here in our Arrow function so they just prefer to just write the code like this so This basically looks a little more lean but I don't want to comment over the readability it is developer's choice and how you follow but I personally like the older syntax with function keyword better right that is my way of coding but some developers like to write code like this all so I just wanted to show you that this code growing horizontally is now converted to this fashionally evenly fashioned vertical written code and a promise chain make sense so this is known as promise chaining and it helps us get out of callback Hill isn't it beautiful my dear friends it's so beautiful promises gives us so many amazing functionalities that what we had to do in our previous callback fashion would have messed up our code so much it just messes up I have seen repositories where a lot of code here and there written in random order and Promises just makes our code much more beautiful and cleaner and generates trust in that transaction so this was a very long video and now let us just quickly recap whatever we studied in this video very quickly okay so first of all we saw that okay how we can handle our async code in using callbacks and there is a major issue in this callbacks while using callbacks that is inversion of control we were passing a function inside another API and we were given control of our program to some other API which we wanted to avoid that was inversion of control and how did we solve it we basically had a promise object and that promise object will be eventually filled with a result of async operation right that promise object and we don't pass a function inside any other function but what we do is we attach a callback function to that promise object and whenever we have data inside or whenever the promise is resolved that automatically that callback function will automatically be called by promises right beautiful thing isn't it and what happens is promise gives us guarantee and Trust in our whole transaction how because you can resolve promise just once and you can only have three states for promises either pending or fulfilled or rejected there is no other state you can pass promise wherever you want to without caring about the mutability of it it is immutable you cannot alter a promise if it is resolved so promise comes with a lot of trust and then we also saw that beautiful looking promise object remember that okay it was a special object right which had two major properties one was the promise State and the other one was promise result which used to hold data remember which eventually get filled right which eventually gets filled right and then I also told you that how do you have to answer a question that what is a promise in the interviews how remember the definition I bet you would have forgotten it right now let me just recap it once again so the promise is an object that represents eventual completion of an async operation eventual completion of an async operation it's very easy just remember it once say it to yourself promise is an object that represents eventual completion of an async operation that async operation will be eventually completed so it's an object that represents it right very easy just say it to three times you will just remember it for life it's so beautiful okay we saw that how do we answer that and the other and then later on we also discussed that okay there is one more issue using callbacks that is callback hell right and then we can use promise chaining right to handle that type of issue and then we have a beautiful looking promise chain with us we can use then to attach a lot of callback handlers for our promise and we can just do that and then I also discuss one more thing which you need to be careful about that whenever there is a promise right inside that promise chain right so you might have to return that promise once again into the chain otherwise you might lose some data in inside the chain right so these were the things which I discussed in this video I hope you liked it and you would see promises the same way like you used to see earlier promises are much more beautiful much much much more beautiful so in the next video I will cover that how we can create our own promise isn't it beautiful right now in this video we just saw that how we can consume a promise right fetch function created a promise and gave us to us right the create order we were assuming that this create order API will give us a promise but now we will in the next episode we will see that how we can create a promise and return from this create order API okay we will try to write our own implementation of this create order API how we'll create a new promise and return it right because I am also a developer I want to create promises and send it around to people to generate trust in our transaction isn't it so we will see that how we can create a promise in the next episode this was about consuming promises that episode is going to be mind-blowing just keep watching Namaste JavaScript season 2 and now it's time for homework of this episode so what you have to do is first of all you have to explain in the comments that what if the interviewer asks you what is a promise how would you answer that don't see other comments just write your own definition with exact same line over there okay what will you answer first question is what is a promise according to you just write it down and then second thing why promises are important how would you explain it to the interviewer write it down that will help you please this this is a very important episode and I am telling you this is the most most important video episode of Namaste JavaScript so I want you to take away a lot of things from this episode if you have if you have doubts about anything just comment it down just see the video once again and just do this homework two questions first is how would you answer a question about what are promises in JavaScript and the second one is why do we use promises what is advantages of it explain it in your own terms in the comments I would love to read all the answers I would give you a heart if I like your answer please do that please do the homework this is really very important it just takes five minutes before you go away from this video please do that and in the next episode I will be coming up with creating our own promises so go check out the next video but finish your homework right now before you move from this video and thank you so much for watching Namaste JavaScript season 2. [Music] the problem subject represents eventual completion of financing Corporation promise object represents eventual completion of an async operation promise object represent eventual completion of an async operation promise object represent eventual completion of anything completion promise object represents a ritual completion foreign
Info
Channel: Akshay Saini
Views: 215,990
Rating: undefined out of 5
Keywords: akshaysaini.in, akshay saini javascript, akshay saini web engineer, akshay saini uber, akshay saini frontend, javascript tutorials, javascript interview questions, frontend interview questions, frontend tutorials, javascript fundamentals, akshay saini js
Id: ap-6PPAuK1Y
Channel Id: undefined
Length: 39min 6sec (2346 seconds)
Published: Sat Oct 08 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.