Javascript Interview Questions ( Promises ) - Polyfills, Callbacks, Async/await, Output Based, etc

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
promises yes ever since i started this javascript interview series i have received a massive request for a video on this topic so in today's video we will discuss call backs call back hell promises promise chaining promise combinators async await and much much more along with their interview questions from basics to advance and the best part is that we will go on to create our own promise implementation yes we will create the polyfills for promise and its combinators like promise dot all promise dot trace promise dot all settled and promise dot any so over here i've opened basic html css and javascript files so let's understand what a promise is so let's take an example over here of a child and his mother so let's say the mother asked the child to clean his room and according to that he will get to go to play with his friends or he will get the punishment so over here the child makes a promise with his mother that okay i will clean the room so a promise has been established over here and if he fulfills the promise then his mother will let him go to play with his friends and if he doesn't fulfill the promise he will get another punishment so this is exactly how promises work in javascript as well so let's say if we are trying to fetch the data from an api we ask for the data from our front end and the api promises us to return some data if we get the data if the promise is fulfilled we can use this data and display it to our user but if it doesn't get the data if it rejects our promise then we are going to display some error so we're gonna go and deep dive into what promises are very soon but let's start from the absolute scratch so let's discuss the difference between synchronous and asynchronous code because promises is an asynchronous code right so you should know the difference between what a synchronous code is and an asynchronous code is just in case if your interviewer asks you this question as well let's take a basic example of uh synchronous code so i'm gonna console.log start finish and in between these i'm gonna put another console log which will say subscribe to roadside coder which you should if you haven't yet so if i run this file so let me run this html file real quick so here it is and i'm gonna go to inspect console and yep you can see this is start subscribe to roadside coder and finish so what's happening over here is our code is being executed line by line so this is an example of a synchronous code but what about asynchronous code so let's see an example of that as well so instead of this what i'm gonna write over here is i'm gonna say set timeout and let's give it i don't know one second so if you don't know if a code is inside of a set timeout it will execute the code after this amount of seconds so for example i have given here 1000 milliseconds that mean one second so if we execute this you're going to notice refresh this you can we get start we get finish and then we get subscribe to roadside coder so why did this happen it's because javascript is a single threaded language and it cannot execute this set timeout in parallel as our code is being executed so what it does is it's gonna execute all of our synchronous code and then it's gonna go on and execute this set timeout because set timeout is a part of our web apis so what happens is when it encounters this set timeout even if we give zero seconds over here it's not gonna run it until our code has finished executing so actually this is a complete different concept which is of event loop if you would like for me to make a separate video on event loop just let me know in the comments down below but i'm gonna briefly explain you over here what it does so basically what we're trying to do over here is we're using set timeout to simulate an asynchronous process so let's say if we were to fetch an api over here that will also be an asynchronous operation right because let's say if you're trying to fetch to-do's in your to-do application which comes from the back-end right so it's gonna execute all of the synchronous code and meanwhile it's fetching that api it's gonna run all of the code and as soon as this code has finished executing it's gonna run whatever code that is written inside of the set timeout so this is basically an example of an asynchronous code don't worry you're gonna get a better understanding of how this asynchronous code works as we move along in this video but you have to remember this golden rule javascript executes synchronous code first and then asynchronous code so let's move forward and take a better example for this so if i take this example right over here so we have a start we have a stop over here and then we have this function called important action which takes a username and inside of this we have this set timeout which just returns subscribe to whatever the username is and over here we are calling this function and we are returning whatever we get from this function inside this message variable so actually i'm gonna right cycle right so and then we are console logging this so what do you think is going to be the output for this so let's see we are first going to print this start okay then we gonna encounter this function okay fine then we will call this function over here cool but remember this function is acting as a asynchronous function since we have this set timeout inside of it right so this won't return anything instantly to this message variable and this message variable will be undefined at this point so this will print undefined and then we will get stop so let's see yep you see start undefined stop so this is also one of the examples of an asynchronous code so what do you think how are we going to run this code so that we get a message inside of this console.log so we're going to use a concept called callbacks in javascript so what we're going to simply do is we're going to take this console.log so basically when we pass a function inside of another function argument so then we call that as a callback so for example over here so i'm going to take a normal function over here let's say it doesn't matter if it's a normal function or an arrow function it's going to work both ways you see we are passing a function inside of this function call as an argument and inside this we can just say console.log message and we're going to take a message over here and then we're going to simply console.log it over here right so we're going to receive callback over here and when we return this instead of returning this what i'm going to simply do is i'm going to say call back and send this as an argument to this callback so what it's going to do is it's going to call this callback over here it's going to send the message and then it's going to console log it right over here let's see let's refresh this so start stop and subscribe to roadside current now if you notice this is coming at the very last because this is an asynchronous code during that time the console log was not inside of an you know asynchronous code right so that's why it was printing undefined instantly but now that it's this operation will be completed after one second after set timeout will be executed only after that this function will be executed also i told you that it doesn't matter if we have zero over here as well this will still be executed after our complete code is finished so if you see start stop and subscribe to roadside coder yep okay so let's take this one step forward and what i'm gonna do is i'm gonna take another function over here called like the video which takes the name of a video and returns like the whatever video it is so what we want to do is we're gonna execute this like the video function after this important action has finished executing so it's simple actually we what we can do is we can simply below this call this function and let's provide it so what this should do is we this should execute this and then after this this should execute like the video and we want to console log it so i'm going to pass another callback over here let's pass an arrow function this time so log put it inside of it pass the call back over here like that like this so now if you go on to run this you're gonna see that we get start stop subscribe and then like the javascript interview questions video which you should like right now and so what we're basically doing over here is what we're trying to do over here is we want to execute this function after this function has finished executing right but if we were supposed to execute this function after it then this would have dependent on when we get the result if you got the result of this first then this will be executed if we got the result of this first then this will be executed let me remove this part we don't need it anymore yeah so let's say if this has i don't know 500 milliseconds and this has 1000 milliseconds so this will be executed first see like that so that is what we're trying to achieve over here and callbacks helps us achieve just that so let's have another function over here called share the video and we're gonna just i'm gonna take this and paste it over here and just say share the video and what will what this will do is this will execute like the video and this has finished executing and this will execute share the video when this has finished executing so now if we see we have first subscribe to roadside coder then like the video and then share the video so that is exactly what we were trying to achieve over here but did you notice something that this nesting of these callback functions has made our code a little bit messy so if we were to let's say if you had more such callback functions right because obviously when we are working in a company or a production code our code won't look this simple right it will have more nested functions inside of it like this so you see this is a weird looking code structure it's forming a pyramid-like structure which is also sometimes called as pyramid of doom and this concept is called callback hell it's because we're having so many nested callbacks one inside of the other that it's very hard to read and very hard to understand our code so what do you think is the solution for this problem yes you guessed it right promises so let's understand what promise is so i'm going to remove this code so promise basically represents the upcoming completion or a failure of an asynchronous event and its resulting value so if you remember the example that i told you at the start of this video that mother child example that the child promises his mother that yes is going to clean the room and according to that he will get the result or the value so if he cleans the room if he fulfills his promise then he'll get to go to play to with his friends but if he doesn't fulfill his promise if he rejects his promise then he'll get the punishment so this is how promise works in javascript as well so let's understand over here so i'm going to create a very simple promise example so let's take const sub equals new promise so we have this promise keyword in javascript promise class in javascript and we're going to create a new instance for this promise we're going to add this new keyword over here new promise and this promise takes a callback which has a resolve and reject keywords inside of it now inside of this we can write our asynchronous code like if we're trying to fetch an api or whatever that we're trying to do that will return some promise which will be fulfilled or rejected so we can write that code over here so for now let's just write our set timeout code because that's an easy example of an asynchronous code right so let's give it 2 000 milliseconds and inside of it i'm gonna take uh a result variable which is true for now and if result is true then we're gonna resolve this promise that means the promise is fulfill and to resolve this we're gonna use this resolve keyword over here so i'm gonna say resolve and subscribe to roadside coder but what if the result is false what if the guy is not subscribed to the roadside coder then we're gonna simply reject the promise then we're gonna say else reject and we're gonna throw a new error new error why aren't you subscribed to roadside coder yeah that's a good question so yeah let's try to run this and how do we run this how do we execute a promise and i'll show you one good thing that i like about promise so if we execute the promise we can say dot then then means if the promise is fulfilled we will get the result and then and if the promise is not fulfilled if it fails then we're gonna get the result in catch so you see how this promise handles error right out of the box so and then i'm gonna say rest and log rest insert this error so i am going to say console.error err so lets see let us check it out and since as you already know this is an asynchronous operation then this will first run the synchronous code and then the asynchronous code over here so start stop and then subscribe to roadside coder great but what if our result was false then we will get an error over here why aren't you subscribed to roadside coder so this is a very basic example of a promise so now you might be able to figure out how that child mother example connects to this question over here now also you might be thinking that we're using this then end cache over here but what if we were supposed to console log this over here so if let's say let's console like this so we get start and then we get a promise object over here which shows that promise is still pending and it has not resolved yet but it will be resolved after two seconds so if i refresh this see it's pending and then it will be resolved to fulfilled and this will give us our value which is going to be subscribed to roadside coder yep you can see just like that we get fulfilled and the message over here so that is why we use then and catch over here which helps us get the result or the error from this now let's say if we were supposed to you know resolve this promise directly without needing to have all of these conditions and all right so let me just take what we can do directly is we can just say promise dot resolve and insert this i'm gonna give this message so this will work exactly the same this will return us a new promise with this fulfilled state so if i you know just directly print this you're gonna see that we get a promise object but this will be by default fulfilled and subscribe to roadside coder and let's see if this is an asynchronous operation or not so if i go on and say dot then oh not on this one let's take this inside of uh let's see so yeah you see it is still an asynchronous operation we will instantly see the state of the promise at that particular moment which was fulfilled but we won't see the result until the whole synchronous code has been executed and after that we will execute our asynchronous code and similarly we can do reject as well yeah you see rejected and we will get the oops we haven't added the dot catch over here so if you are supposed to dot catch so catch and now if we go to our browser yep you're gonna see that we have a rejected promise over here and then it goes to the dot catch block okay so now let's get back to our previous code that we had written let me bring that back this one right over here and let's implement this with promise let's see how promise makes this code a bit cleaner so what i will do is first of all i'll remove this thing and for these functions i'm going to make a little bit change in this first of all i'll remove all of these callbacks and instead of this i'm going to say return new promise and as you know this takes two things resolve and reject now let's take this and put this inside of this and instead of doing this callback i'm gonna say resolve over here and that's all uh we can also add a reject condition if you would like but let's let's just focus on resolve for now and i'm gonna rewrite these two as well just like that so we are returning promise over here as well and resolving it cool now let's see how we can call these so first of all for this one let's make this one second as well so i'm going to say important action and so we're supposed to provide this a value so and so what are we supposed to do after it if it's resolved then we're going to say dot then and if it's not resolved if it's error then or if it's rejected then we're going to say catch cool just like that oh not cr response and error will be over here here i'm gonna simply do response so now if we go on and see we'll get subscribe to roadside code we're gonna get this start this stop and then the asynchronous code that is this code right over here now if you're supposed to you know execute this like the video function we're gonna have to follow the same approach that we were following in callbacks so after this is resolved we can do this like the video and just give the video name and then i'm gonna say dot then result and after this for share the video as well let's again share the video so you see now it's much more cleaner approach we are not supposed to you know pass callbacks to these function as an argument we can just do dot then and then after that we can pass another action and then we also have this error handling right over here let's see yep you see one after the other this will be executed sequentially but then you're gonna tell me that but this is again that pyramid-like structure right then why are we using promises in the first place if we are again supposed to you know deal with this pyramid-like structure don't worry we have more than one approach to do this in promises one of which is promises chaining so let me remove this code for now just keep it like this i'm gonna remove this catch block for now so you see what's happening over here is we're calling this promise and then we're resolving it right now after that what we can do is we can say like the video and we can provide it the param to avoid having that pyramid-like structure what we can do is we can return whatever the result of this function is so we can say return and we are returning a new promise over here so then what we can do is we can chain another then after it not after this function because if we did that this was going to create that pyramid like structure right so that's why we are returning it over here and then we are chaining another dot then so now if we response and let's check the response over here and now let's see yep we get the output and simply we're gonna return another promise over here like that and we're gonna have again a dot then like that and console.log response and after that i'm gonna put a catch block just in case if we get any error like that so you see this code is much much clearer than our previous approach so if we save this nc start stop and we get all of the message one after the other so this concept right over here this is called promises chaining so what why are we calling these promises cheney because we are chaining these promises we are returning a promise and then we are chaining another promise one after the other as we return the value for the previous promise so that's that is why this concept over here is called promise chaining this can be asked in your interviews as a standalone question so you should be prepared for this or interviewer can ask you a output based question on this as well which obviously we're gonna discuss later in this video we're gonna discuss interview questions for all of these concepts that we are understanding over here so now you might be thinking that this is also a pretty lengthy way of doing it isn't it so that's why we have one more approach in promise which is called promise combinator which will make our work super easy so let me show you so i'm going to remove all of this you know what i'll just remove i'm going to keep this and i'm going to keep this all of our promises and i'm going to remove everything and this out for now now so we have something called promise combinators so what are promise combinators so promise combinators basically helps us to execute more than one promise at one time and then return the result accordingly so there are four types of promise combinator one is promise dot all so what promise dot all helps us to do is so let's say if we have provided multiple promises to promises dot all it's gonna run all of the promises in parallel and in the end it's gonna return the array with all of the fulfilled promises but let's say if any one of the promise failed then it's gonna fail the complete promise.all so that is how promised.all works so let's see this in practical so i'm gonna say promise dot all and this takes an array of all of the promises so let's copy this up and paste it inside of it and sort of semicolons i'm gonna provide it just like that cool so now this basically will return us a promise with all of the fulfilled promises inside of an array so let's uh you know what let's just console.log this first let's see what we get so we see we have a pending promise over here and we got it fulfilled with three items inside of this array all of our promises have been resolved over here awesome so let's what i'm gonna do is dot then the log result and also catch for handling our errors like that yep so you see we have this result inside of this array that was returned to us in this dot then block but as i mentioned if any one of these promises fails all of this will fail so i'm gonna say reject and you know what i'm not gonna give error over here let's just give a custom error message over here error promises failed and now i'm gonna give which promise failed yeah so let's see yep you see start stop and promises failed and this gives us this like the javascript video promise failed but you shouldn't fail to like this video so hit that thumbs up button right now so um this won't go into this dot then block even if all of the promises succeed even because if even one of the promises fail this is going to fail now the next promise combinator is promise dot race so how promise dot race works is its syntax is exactly like promise.all but this returns the first promise that gets fulfilled or rejected so let me show you race so if any one of these promises succeed so i'm guessing this one will succeed first so this will return it over here so let's see yep you see but let's say if this promise was supposed to you know get fulfilled first i'm going to give 500 to this obviously this will make it resolve earlier so yeah you see but let's say if this was resolved first so this is reject so i'm going to give this 100 milliseconds so yep you see we only get that promise that gets rejected or resolved first so that is how promise dot race works and again guys i'm gonna teach you how you can create all of these promise combinators from absolute scratch because that is also a very important interview question as we go forward in this video so don't you dare click that back button now the next promise combinator is promise dot all settled which again has the same syntax but the functionality is a little bit different so this actually work exactly like promise dot all but even if any one of the promises fails it's gonna return all of the promises that are fulfilled as well so in promise.all if any one of the promises fail it's going to fail the complete promise.all right but in this one if any one of the promises fails for example let's say dislike the video fails so let me show you if i go it's going to return all of the array items so this first one was fulfilled second one was rejected third one was fulfilled so that is how all settled works it works exactly like promise.all but it's gonna return the failed promises as well as fulfilled promises now the fourth and the last one is promise dot any now this is exactly like promise dot race but what it does is it only returns the first fulfill promise and ignores all the rejected ones so if let's say this like the video was supposed to be completed first so yeah 100 millisecond but this is going to ignore this one and it's going to move on to the next promise that will get fulfilled that is this one so let me show you yep you see share the javascript interview video but what if all of the promises fail so let me project only then this will give that okay promises all promises were rejected so just keep all of these points in your mind we're going to need all these points when we go on to create their custom implementation or polyfill for all of these so awesome these were four promise combinators and these are really important for our interviews because interviewer asks these questions very very often to try to understand your javascript code javascript knowledge now let's move towards more modern approach of handling promises that is with async await so let me remove all of these all of this code right over here so let me show you how async await works and helps us so this is one of the best approaches when we want the promises to you know be executed one after the other so first of all let me fix this so okay so let me create a function over here const result i'm going to keep it an arrow function you can keep it a normal function doesn't really matter and now inside of this i'm going to say const message 1 and i'm going to call our promise over here important action just like that so this promise will be executed over here but we're not going to use dot then to get the result right but if we wrote it like this this is going to return us the promise object which we don't want we want the result from this right so what we're going to say is we're going to say a wait so what await is going to do is it's going to wait until this promise returns us a fulfilled or rejected whatever state and then we're going to get the value and provide it to this message variable and since we are using a weight over here this function is supposed to be an asynchronous function which we can do it by adding async keyword over here in a normal function you can do this function and the name of the function whatever it is and just like that so let me remove that so yep this is how you write it with async awaits let me call both of those functions as well yep so what this will do is it's gonna wait for this to finish then it's gonna move on to this one and then it's gonna move on to this one and now if i simply console log this with all of these three message one then this will give us the proper output so start stop it's waiting for them to get us oops bad i didn't call this function yeah now let's see start stop and then yep we get all of these three promises resolved over here but let's fail any one of these promise so reject now let's see okay it's going to give us the error like the javascript interview questions so but we haven't you know handled this error properly so how do we handle an error over here when we are not using then and catch so we're going to use something called try catch so we are supposed to write our code inside this try block and if this try block fails then it's gonna go inside this catch to show the error so promises failed and i'm gonna say error over here okay let's see now yep you see promises failed and it gives us the message which promise failed the rejected message so yeah i feel like this is one of the most cleanest way of resolving promises with async await and also promise combinators works like a charm as well now if you want all of these messages to be executed instantly after this promise is executed you can just simply provide console log over here so this is very flexible to work with just one after the other you can provide all of your output so that you don't have to wait for all of these promises to fail so yeah we get the first output and this failed over here so that's why it jumped out of it over here and then it went inside this cache block so right that's all the theory part that we needed to discuss for this video now let's move on to the most asked javascript interview questions on callback promises async await etc but before moving forward if you are preparing for front-end interviews and you would like me to help you in your front-end interview preparation you can book a call with me by clicking the link in the description and choose the slot which suits you the best we're gonna discuss all of the last minute preparation tips i'm gonna guide you throughout how you can prepare for your front-end interviews all of the tips tricks and all of the most asked questions and i'm gonna provide you a lot of resources that you can use to prepare for your front-end interviews so just click the link down in the description below and book a slot with me okay so now let's move on to the most asked interview questions on promises so here's the first question over here and we have to tell what is the output for this question okay so we have this console.log start then we have this promise initialization where we say new promise and then we have a console log inside it and then we are resolving this promise by two okay cool and then what we're doing is we are calling this promise by dot then and then there is this end so actually i want you to pause this video right now and try this question yourself first before moving on and then continue with the video to see if your answer matches with mine so i hope you are able to do this question let's see the solution for this so most people when they see a question like this they will think ok this will print start then it will initialize this promise that means it will print console log 1 and then this is resolving the promise so we are going to resolve the promise over here and then print 2 and then the end so that's right let's see no this will print start 1 and n2 so few people think that we will print start first then maybe because this is an asynchronous code this will print start and and then 1 and 2 because obviously this is asynchronous code right but no that's not the case when this promise is initialized it's gonna find whatever synchronous code is inside of this so if you remember javascript engine always execute synchronous code first and then the asynchronous code so this is the synchronous code and when this is encountering this promise when this prompt is being created this is the synchronous code so this will print console log okay fine and then after this so this is resolving over here but this will not instantly print it right this will only be printed when we do this dot then which is an asynchronous operation and then we will print end and then at the last this will be executed inside of dot then because promise is an asynchronous operation and asynchronous of operation always runs after synchronous operation is finished so therefore we will have this output start one and and two so here's another question which is also what's the output question so if you were not able to do the our previous question so this is exactly same as the previous one the only difference is we have a console log 3 over here so what do you think is going to be the output we're gonna print first start and then it will create a new promise inside of which it will encounter the synchronous code so that's when we will print console log one then resolve two and a lot of people think that okay maybe since this is an asynchronous operation this will also be printed at the very last so that means start one and and then two three but that's not the case we are going to print start then one then three then end and then the asynchronous operation that is resolve that is this one at the very last so this is the only thing that is asynchronous over here because these two are synchronous and can be instantly executed while we are initializing our new promise so let's see yep start one three and two awesome now before moving to our next question i'll i'd like to tell you that there can be another variation of these questions where interviewer can confuse you by removing this resolve altogether then what do you what will you think that the output will be and let's say he puts a result so you may think that this will print okay start one three and then end and then after that result and there is no result right so it will be undefined but that's not the case since there is no resolve it will not go inside of this dot then block so if you see start one three and end so don't confuse this when the interviewer does not give you a resolve inside of a promise this will not go inside of this dot then at all now here's another output based question so in this the interviewer has added this fn function to confuse us so this has a start and then this fn function then we have this console.log middle then this fn function is being called and then we have the end so this function is there to confuse you so many people will think that okay we'll print start and then we'll print console log and then middle and then this is obviously an asynchronous operation so we will print end and then after that we will print success over here right but don't miss this part that function is being called after this middle so we'll print start then middle and then this function will be called so this console log 1 will be printed when this new promise is initialized and then after that we'll print end and then we will print success so now if we see yep so these are pretty easy output based questions right but don't worry this is just the beginner level i'm gonna increase the difficulty of these questions as we move along and you have to try them along with me all right pause if you're not yet following me on twitter go to twitter.com push underscore eon or click the link in the description down below and hit that follow button right now i'm waiting for you i'm still waiting okay fine let's continue with the video so here's our fourth output based question and this is actually on promise chaining so we have a function over here which returns a new promise instead of which we have this reject function over here okay and after that we are calling this job function and we are assigning it to this promise variable okay fine so this will return a new promise inside of this job function that is inside of this promise variable so then we have this promise which we are calling and then we have a bunch of dot then and dot catch methods and if you remember this is what a promise chaining is right so let's see what's happening so this will reject the promise okay so we will have a rejected from inside inside of over here so when we call this so this will not go inside this dot then not go inside this dot then not insert this dot then it will go inside this dot cache over here so this should print error 1 and then it will print success 4 because there is this dot then attached to it so a lot of people who didn't know what promise chaining is they might get confused with such a syntax and they might not know what to do but it's simple we're gonna just do dot catch and whatever the result is since in this case we are not returning anything so we're just gonna go inside this dot then block and print success four okay cool so let's see yep error one success four okay let's try a little bit advanced version of this question so here it is so let's take this one by one this might be little confusing to few of you so we have this question over here job and inside this we are creating a new promise again and returning it and we are taking this state as a parameter and if the state is true we are resolving success if the state is false this will be reject error pretty self-explanatory right then after that we have this variable promise inside of which we are calling this job function so this job function will return a promise inside of this promise variable so job will be true so that means this will return resolve success cool okay we have the resolve success inside this promise so when we go inside this promise so this will be dot then obviously since it's a resolved promise it will it will go inside the dot then so i'm gonna say this will print which is this success over here right so it's returning this success so this will print success first okay fine then this is gonna return job false okay so this is calling another promise over here and this then this is returning as we discussed in our promise chaining part right so we have this job false over here okay cool so this will reject the promise and return error fine so this will now return a rejected promise so this will go inside of the cache okay cool so we have catch just right after it so we will go inside of the catch it will print this error variable which has this error inside of it since we are rejecting the error right so let's print error cool now after this we are returning error code now since we are returning a string over here obviously this is not a failed promise so this will just be counted as a resolved promise so then this will go inside this dot then block and it will print error court over here so error caught and then after that we are returning job true which will obviously be again returning this resolves success but after this if you see we don't have any dot then block so this will go so this will not go inside this dot catch and the code will end here so this should be our output let's see yep success error and error code awesome all right so now this is even more advanced version of the previous question so i want you to do this first let me show you the complete question over here so we have a function job as previously and we are calling this function over here and then we are resolving the promises right over here let me make the font a bit small so you can see the question and then try it yourself so just like that all right so i hope you were able to do it so we have this job function which we are calling over here job true right so this will return resolve success as previously write it over here and after this we are taking this promise variable and then we are chaining a bunch of functions after a bunch of dot then and cache functions after it so then let's see so this is resolve success right so obviously this will print this thing right over here cool now after that we are again saying return job true so this is again a resolved promise right so it will go inside of this dot then block over here and now it's checking if the data is not equal to victory which is obviously it's not equal to victory it's equal to success so this will throw defeat now this is throwing an error to us so this will be a rejected promise from now on so even though this is returning job true we are going to ignore it because we are saying throw defeat so this will not go inside this dot then block it will go directly inside this dot catch block which will print error which was defeat so i'm gonna print defeat over here now moving forward this is returning job false so obviously it will return this rejected error so then it will not go inside this dot then block it will go directly inside this dot catch block and it will print this console log error which is going to be this thing error now this is returning error caught and even though it's written error caught over here this is just to confuse you because this is an resolved promise right this is not a rejected promise so this will go inside this dot then so now instead of the dot then this will print this data over here which is this error caught then we are returning this new error test which is again just to confuse you this is not a rejected promise this is now normal text so new error test so this will go inside this dot then block and it will print success test so let's see the output yeah we got the exact same output so this part can be a little tricky that the interviewer put to confuse us but now you know how to do them now here's another question on promise training actually there's a bit of explanation required that's why i haven't written the question over here so what interviewer has asked us to do is it he has asked us to create a promise called first promise which will resolve to a text called first and then we have to create another promise called second promise which will resolve our first promise that we had created earlier then what we are supposed to do we will resolve our second promise and output of which we have to pass to our first promise and then print the first promise so let me show you what we're supposed to do so const first promise equals new promise like that and instead of this we are supposed to resolve it by first okay then we have to create another promise called second promise and this will resolve this first promise over here so i'm gonna paste it right over here so then what we're supposed to do we're supposed to call the second promise okay second promise dot then result okay so we don't need to console log anything over here because we are supposed to invoke this first promise through the second promise so we're going to say result and we can also say like this return result okay so this will return result right then we have to pass this that this has been resolved and whatever prompt is that this will return so this will return this first promise over here right so we can do dot then again and result console log result now i know it might be a little bit confusing to understand this question at first i was also confused when i heard this question for the first time so you have to ask your interviewer a bit more explanation what he's trying to ask you to do when we do dot then like this it will print this first over here yeah we got this first so the the only purpose of this question is to understand that you know the concept of promise chaining or not okay so for our next question the interviewer has given us this code snippet over here and we have to rewrite this example using async await so if you remember i explained what async await is and how it makes our life a bit easier so let's try to write this code by using async await instead of using dot then and catch so we have this load json function over here with this url and we are returning this fetch url so what we can do is we can just take a variable called response and we can say wait fetch and we're going to give it url over here right let me comment this out we're gonna wait for our fetch to finish fetching whatever url that we have provided this and get the response inside this response variable over here now we're gonna check if response dot status is 200 that is it works we're gonna have the response inside the json and then we're gonna simply return this json otherwise we're gonna throw a new error over here now oops i forgot to add async over here yep so you see how clean this code looks now earlier it was having dot then and all those chaining and stuff right now it's much more clear that if response is 200 return this otherwise it's going to throw a new error so this is a much cleaner syntax and this is a very basic example let's move forward okay so for this next question the interviewer has asked me to create a function called prom recurs which takes promises in form of an array and resolves them recursively so this function is going to use recursion to resolve all of the promises so let's say we have a bunch of promises let's take our previous example of all of these promises important action like the video share the video all of that let me minimize them for now so we have these three promises right how can we pass them to this function so that they can be resolved recursively so we're going to call them just like this so we have to write the implementation over here let's see let's see what we can do so first and foremost we have to check all of the edge cases right so one of the edge cases is if the function that are provided to us we have to check if they are equal to zero that are we even provided any functions or not if this is empty then obviously we are not going to do anything right so if this equals to 0 we are going to say return that's all right after that is being after that's handled what we're going to do we're going to say const let's say current promise and i'm gonna assign one promise to this so function.promises.shift now if you don't know what shift does let me show you so if we have an array called one two three and let's assign it i don't know let's temp variable right so if we say temp dot shift and then we call this we're gonna get one and this will be modified and this won't have two and three anymore so now if you print temp yeah you see so it removed one from it and now it has two and three from let's continue so now we will have the very first promise that is this important action promise inside of this current promise right now we can say current promise and we can resolve this right over here in console.log result and if there's an error i'm going to say dot catch and handle that error right over here awesome so we have taken this promise and resolved it over here yeah that's pretty simple but what about the result remaining promises right that are inside of this variable over here so what we're going to do we're going to call this function again recursively so this is going to pass remaining promises to this so in the next iteration what's going to happen is it's going to have these two functions then it's going to resolve this one then the third addition is going to have this function so it's going to resolve this and then again it's going to pass it to this function and then in the last iteration it's going to encounter this function equals to 0 then it's going to return simply and then our implementation will end so let's see we have the subscribe like the video and share the video all of our promises have been resolved recursively so this is how you can do this implementation okay so now finally the time has come that you all have been waiting for we are going to create the polyfill for our promise yes we are going to create our own promise inside of which we can use dot then dot resolve we can use promise dot resolve promise dot catch and all the functions that are available to a normal promise so we have this function called promis polyfill and it's going to take executor so executor if you remember what is executor is so let me write a basic example for a promise which we're going to run later and we have new instead of writing promise now we're going to write promise polyfill and this is going to take resolve and reject so this is what our executor is and inside this i'm going to simply return set timeout i'm gonna simulate a promise over here right simple and then simply we can take this example promise and say dot then and it's gonna be resolved over here inside this console log also this can have a dot catch as well we're going to test all of these things out when we have created our polyfill so let me comment this out for now and let's start implementing our promise polyfill now let's see what are all the things that are required to create a promise polyfill first of all that we have discussed that it needs to take this function with this resolve reject so which will be called as executor right then after that when we call this promise this should have this dot then and dot catch functions after it which we can chain after it so what we're gonna do for now i'm gonna have let's say this dot then which will be obviously chained after the promise when it's being resolved so i'm gonna say this dot then it will be a function anonymous function which will take a call back because obviously when we do dot then we have a call back inside of it right which we're gonna use now and we're going to have a variable over here let on resolve and when this is resolved i'm going to say on resolve equals callback and then simply we're gonna return our this that is our promise polyfill class cool oops i mean return yeah and similarly we're gonna have a catch as well so oops this dot catch and this will be another anonymous function this will take a call back and this is going to return this as well don't worry i'm going to write all the complete implementation for this in just a minute i am just trying to create a simplified version of the same thing now apart from this we are providing this executor to this promise polyfill right so we are supposed to provide this executor with this resolve and reject so over here we will have this executor which will have resolve and reject so we will have two function as such first function will be resolve which will have a value which will provide while resolving it like this now when this is resolved so i am going to say on resolve value and similarly we are going to have a reject as well like that and actually we're going to have an on reject variable as well so here we're going to say on reject don't worry i'm going to explain everything as we go forward just bear with me for now and this function will be called reject right so this is a very basic things that i'm trying to cover for now so that we have a structure to work with and you know what inside of this dot catch as well i'm going to write on reject equals callback and we're going to write the further implementation later now you know what let's uh let's test this out obviously the dot catch will not work because this will require much more than what we have written up until now so let me just remove the comment and let's see what do we get up until now yep we get this 2 over here so we are creating this new instance of this promise polyfill right over here and then we are having this executor function over here right with resolve and reject okay fine now after this we are calling this dot then now dot then will have this callback which will take this response and console.log this response okay so when we go inside this dot then we have this callback and we are assigning this call back to the on resolve variable so now the on resolve variable is a function which will take this response over here so we are returning this so we have returned this instance of this promise dot polyfill now we can access all of these functions inside of this promise polyfill right so now if we go inside of over here we have this resolve two so this will call resolve over here and now if you remember resolve walls was a callback so this will be provided this two variable over here now inside this on resolve we are providing this to variable cool and then we are calling this on resolve so therefore we are printing this console.log resolve so this is a very basic implementation of this thing now let's move forward so what we have done up until this point is for the asynchronous operations right when we do this dot then but let's say if we don't have this set timeout or we're not calling an api and we're just directly resolving this then what's going to happen it's not going to go inside this dot then so it will not provide this callback to this on resolve so this will give us this error that onresolve is not a function because obviously inside of this resolve over here onresolve is not a function anymore it's it's just a variable because we haven't initialized it with a function so let's handle the synchronous part of this thing as well now before that i'm gonna take a few more variables over here first one will be is fulfilled just to show if there's been fulfilled or not and by default it will obviously be false and we're gonna have another one which is is called and we are gonna have a value just like that and i'm gonna tell you what value will be used for later so first of all whenever this resolve is called i'm gonna say is fulfilled is gonna be true because obviously when whenever this resolved is called our promise will be fulfilled right so offset is fulfilled to be true and we are going to use this is fulfilled later on and then the value will be equals to value or let's call it val this one as well to avoid any confusions later on cool and also if you can recall in synchronous operation this will not be a function anymore right so we're going to check first if resolve on resolve type of on resolve actually type of on resolve is equals to a function if this is equals to a function then only we're going to call this onresolve over here and we're going to said that this is been called that is called to true we're going to said that this resolve and this function that is on resolve has been called we are checking we are putting this is called for checking this on resolve function which is indicating that this callback right over here has been called so now next if we try to you know run this with this synchronous code obviously we're not going to get any error cool so we've resolved this error for now but we haven't yet executed our onresolve function over here right in the case of a synchronous operation then what are we going to do so in this case we're going to since this is not going to be a asynchronous operation the dot then will be called later on so then we're going to go inside this then block and i'm gonna say if if it's been fulfilled that if if the resolve is called and if it's been not called that is it has not gone inside of this and this is an synchronous operation so i'm gonna say if ready to go yeah is fulfilled and not is called right then what we're going to do we're going to say called equals true in this case we are putting the called equals true over here so that we know that this is an synchronous operation and then we're gonna put the called equals to true and then we're gonna say on resolve because now right now this is been initialized with this callback right don't worry i'm gonna explain all of this stuff once again if you are unable to understand don't worry just bear with me for a minute i am going to explain you all of this and if you remember we had initialized our value with this val so now we can use that value over here just like this and i think that's all let's see yeah we see we get this uh returned value over here and if we uncomment this out now it's gonna work for synchronous i mean asynchronous as well so it's working for synchronous and asynchronous as well both of them cool so this was the completion of our resolve and dot then code let's complete our dot catch code similarly dot catch and this uh reject function so in the same manner we're gonna have this is rejected as well similar to is fulfilled so if we go inside this reject we're going to write is rejected to true and value equals to val as previous and again we're going to check just like this so this will be on reject if this is a function then only we're going to call this so i'm going to put it inside of here and we're going to say called in this case as well we're going to have the same variable because obviously this can be called only once either in then or in catch so called will be true and our this dot catch as well we're gonna check like this if it's fulfilled and if it's not called then it's called equals true and onreject will be a value so i'm gonna add this code right over here just like this and they should work for the rejected promises as well now if i let's say reject see okay this is working for asynchronous let's try for the synchronous as well yeah it works absolutely the same awesome and also we are supposed to handle the errors over here as well we have to do error handling before the executor so i'm gonna say try catch if everything goes well we're gonna execute this executor but everything if anything goes wrong we're gonna say reject yeah that works fine i guess this looks good and that is all that was the implementation for a promise polyfill so let's go through it once again once more ok so we have this promise over here we have creating we are creating the new instance of this promise polyfill with this callback with resolve and reject i'm going to go for resolve first i'm going to explain all the conditions right because obviously the reject condition is is exactly the same as resolve so i'm going to explain you there is just the resolve condition over here so what we're doing is we have this executor function over here which we are passing to this promis polyfill and after that we are calling this example polyfill by using dot then and dot catch so what it's gonna do it's gonna create a new instance for this promise polyfill with this executor and now insert this we are calling this with dot then now i'm talking about asynchronous operation over here so in the asynchronous operation this dot then will be called first so insert this dot then we're gonna assign this callback what's the callback this one right over here this is the callback which will be assigned to this oops on reject over here right now it's going to check if it's fulfilled or if it's not called so is it been fulfilled no it's not been fulfilled up until now and is it called no it's not called either so it's not going to go inside of it and it's simply going to return this now when we return this we're going to insert this executor also we are calling this executor right over here with resolve and reject so that we can run this function which is this so we're going to call this resolve over here and insert this resolve we're gonna say is fulfilled to true and value equals val and then i'm gonna check if it's a function yes it's a function so i'm gonna call on resolve to val and when it's called with this value it's gonna go inside this response and we're going to print 2 simple as that so this was for asynchronous operations but for synchronous operations when this doesn't exist what it's going to simply do is it's going to call this resolve first so it's called this resolve first it's gonna put this is fulfilled to true value equals val and right now this is not a function because we have not called dot then yet so we're not gonna go inside of it and then we're gonna come to dot then over here where we will put this callback on onresolve and then we will check is it fulfilled yes it's been fulfilled and is it called no it's not been called so i'm gonna put call equals to true and we're gonna call onresolve which will in turn watch what it will do is which it will print 2 over here simple so that was our promise implementation now if you want to implement this you know promise dot resolve which we discussed at the start of this video what we can simply do is it's very easy i'm just going to bring in the code over here you can take your promise.polyfill and say dot resolve we're going to assign a key to our promise polyfill which will return a function with a new promise inside of it and this we are returning a promise inside of it since we haven't put this curly braces if we put this curly braces we have to write like return new promise and this will directly call this value so we are directly resolve this resolving this value and if we duplicate this we can do simply for reject as well so reject and reject just like that this is pretty easy so yeah this was our promise polyfill and this is a really really important question when it comes to intermediate and senior developer level interviews in junior interviews it's rarely asked but i feel like you should know this all right so for our next question the interviewer has given us to create the polyfill for promise dot all so if you don't remember what promise dot all did was let me tell you a bit uh example over here let's say we have our those original promises over here all of these three promises and if we need to resolve this what we needed to do promise dot all and we're gonna call this inside of this array over here just like this and i'm gonna say dot then log result and you see we have all of these three promises resolved over here so what we simply need to do instead of this promise dot all we need to create an implementation called all polyfill and we need to call this ride over here and this should work as expected obviously right now it won't work since we haven't created our implementation so let's go on i'm going to comment this out for now right so first step will be to return a new promise only then you'll be able to do this dot then and dot catch so return new promise and you know what you can also use our promise implementation that we have created and add this all polyfill to that one as well that's gonna work in the exact same way anyways i'm gonna use the promise for now so i'm gonna have the executor resolve reject cool so we're gonna return a new promise that's the basic thing that we need to do now if you remember our output was in the form of an array and also our input was also in the form of array so this promises will be this array of promises so for our output i'm going to take a new variable const result equals an empty array cool now i'm going to say if promise dot length now if this doesn't have any length that is this is an empty array then we're going to simply resolve it with the result or let's say results right and i'm gonna return it simple because obviously we don't need to do anything if this promises are empty if this is an empty array right and after that we need to know what's the length of all of these promises is so i'm gonna have another variable i'm gonna call this pending promises dot length and i'll tell you in just a second why we are doing this and now after this we're gonna go through each of the promises and resolve them one by one so i'm gonna say promises dot for each and i'm gonna take two things first the promise and the index now as we encounter each promise are going to resolve it one by one so i am going to say promise dot resolve oops i mean this promise dot resolve and i'm going to provide this promise over here and we're going to say dot then and now some people will say that there are some other ways to do this polyfill as well yes you're right there are many ways to do this polyfill as well and i'm going to include all of those ways in the blog that i've written on this topic on this promise interview questions topics so you can find that blog by clicking the link in the description down below but let's understand this current implementation for now so i'm gonna say dot then and result i'm gonna say results variable which was right over here and i am going to add this result to this results variable so index equals result and now i'm going to move this pending so this spending was on the top of this current length right let us say currently its length was 3 so now i am going to move to another promise so i am going to say pending minus minus but lets say if we have executed all of the promises and this is finished and all of this promises are finished and pending is now at zero so i'm gonna check if pending is equals to zero then we're gonna resolve our complete promise by saying resolve and providing this results variable to this cool and apart from this if there's any error whatsoever in this implementation i'm gonna say comma reject simple and i guess this should be good enough for us let's let's try this out i'm gonna uncomment this out and let's see um assignment to constant variable oh okay i'm gonna put this let not const obviously because we are doing minus minus over here uh yeah there we go we have this result for our promise.org implementation and you know what i'm gonna fail any one of the promise because obviously if any one of the promise fails all of them should fail right so reject and you see all of them have failed over here but we haven't handled the dot catch part error and console.error and i'm gonna say failed like that let's see yep failed and whatever the message that we had provided over in that promise awesome so yeah that is what we were expecting from this and this is what the promise.all implementation is and trust me this is one of the most asked question when it comes to promises in all junior seniors any type of interview it is asked a lot in this interview i i cannot stress on this fact on how important this question really is so cool that was promise.all implementation also i'm not gonna discuss promise.racepromise.all settled and promise dot any in this video because they are not that frequently asked but their implementation is kind of similar and is simpler when we compare it to promise.all so that's why i've included the code and explanation for all of that in my blog link for which you can find in the description down below but still if you like want me to make another video on just the promise polyfills let me know i'll create another video in which i'll include promise implementation promise all uh race all settled and any a completely different video for that but if it's good enough then yeah cool so yeah that was all for this video and again if you're preparing for a front-end interview you can book a call with me one on one where we can discuss all of the tips tricks and i'm gonna guide you on how you can effectively prepare for your front-end interviews and ace them so like this video if you found this video helpful and subscribe to the channel for more such awesome javascript interview videos
Info
Channel: RoadsideCoder
Views: 50,675
Rating: undefined out of 5
Keywords: javascript interview questions, frontend interview questions, javascript interview questions and answers, promises in javascript, callback in javascript, async await in javascript, promise.all javascript, javascript promises explained, javascript promises, promise.then, promise.all polyfill, promise polyfill javascript, async await javascript, promise.any, namaste javascript season 2, web developer interview, web developer interview questions and answers, promise.race, namaste js
Id: HaJdoFp2OEc
Channel Id: undefined
Length: 67min 24sec (4044 seconds)
Published: Sun Sep 11 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.