Javascript: Closures VS Promises VS Async/Await VS Generators

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello and welcome to a video where we will be looking at the difference between closures promises of sinkhole weight and function generators so getting right into it we need to understand the difference between a synchronous programming and synchronous programming so just to make it really easy a synchronous is anything that doesn't run in the main application thread and synchronous does synchro's programming would be something like the following where we defined some kind of number where would be put to five and then we might increase that number by one and then we could log it as so and here we log it and we get the value 6 and this is synchronous because each line is done one after another until we get the result we wish a synchronous would be using some kind of a synchronous method in this case we could use set timeout as an example where the first parameter is an anonymous function and second parameter is the time which is in milliseconds and for example in 1,000 milliseconds this anonymous function will be called and in here we could do log value 5 as you can see we get the value 5 after one second if we decided to do hello and then we do log world obviously world is going to be first because it's because it's synchronous and this one since it's asynchronous it's gonna be called second because it's only called after 1000 milliseconds or one more second so now we don't understand the difference we can actually look into as to why closures or callbacks were created so closures and the pretty much the same thing closure is just a fancy word to say something that will end a function will close the function so for example we could do some some some fetch request they will take in a callback so this is this is how things were done when when JavaScript was first created the original way of doing things and that would be inside of here before we actually did a request we would we would write a prepare a quest with the new XML HTTP request like so and then we would write if this dot ready state before I actually do that I need to do and then what we need to do is request dot on ready States not change so when the state actually changed of the request we check to see if the ready state is actually equal to XML HTTP requests that done and if that was good then when we do this dot status equals equals 200 to see if the request actually worked and if it worked then well we have our response which would be some somewhere here just that response text but we couldn't actually just simply do return because we're actually in a callback function yes of course you could do the XML HTTP request synchronously but that isn't really good because it blocks your whole application right and some network requests you don't know how long it could take to do so we actually put it in some kind of a synchronous function and but this doesn't really work because we actually returned it to this and that doesn't really make sense well it doesn't make sure you turning returns to nothing his question is how do we actually send this data back to out of this function because we can't simply just do for example the data from the fetch equals some kind of a fetch request and then we yeah you can't you can't just simply do that so that's the reason why we have this callback callback seems simply is simply an anonymous function that we'd be called with the data so instead of two like nothing and we have like the results which could read the data and we do data results at this moment we've actually said it like that and to call it we have the callback which is this anonymous function again yeah we simply do call back when the response worked when the net1 of requests succeeded but as you can see this is already getting not really pretty we have some conditions within conditions and you know who-who doesn't say that we could have some other kind of call back inside for like we could have a set time inside which is like another callback and you can have make another and all of a sudden we have like these callbacks ten callbacks callbacks and this is not really pretty so what I'm getting to is the whole point of creating for example promises was to solve this previous problem where we had we could have callbacks within callbacks a promise is simply when some promise a promise is simply something that returns a promise so we would create the new promise which actually takes into parameter a callback and we will put resolved and reject now this is really nice because here what we could do is we could do like for example some a synchronous method with that kind of call back inside and after 1000 seconds we could simply do resolve our data I'm just making some fake data okay and then all we would have to do to use it afterwards this is where it comes nice in handy is we just simply used dot again and here is the data that gets sent back into the resolve function so when whatever you decide to do succeeded you would send the data you would call the resolve function was just simply like a call back to in passed the data you wish to send back and then you could just log into the temple and here we would see data in the console log and if there was an error you would reject it you would send reject and reject would be caught simply by the catch method where we have the error I am you could longer in this case it would be would be the stream data like this but most errors are just simply an object with a message and we write some message there occurred and here we do error dot message and we get this some message error occurred so all this is really nice and we can actually see how it works with our fetch request now fetch like like any fetch today in JavaScript actually returns a promise so we do our fetch requests we send we called the API or the URL whatever and it returns our results and we think just see what that result is we just luggage example can log it and you can see here if there's a response and it has some stuff inside of it and the first thing you can see exactly what's inside of it here but I do know that if this is an API that returns some jason and it is an api to return some jason well the response will have the dot deduct jason method to actually transform the body into some jason now dot jason also returns a promise so that means that i can also do dot then and have the data available and simply consult now here's this is where the advantages over callbacks phone call box within callbacks is that it looks like it's line after line after line and you don't have like this you know function within function with some function which becomes really unreadable after a while so here i can run it and i have my data here stat a success message and then i have an image of a nice little dog so this is how promises work once we understand this part i'm going to put this into you just comments real quick we can start understanding what a sink and a weight is that's think in a way is just from in my opinion this is a shorthand for promises because in a sink some steampunk returns a promise right it returns a promise did I do wrong function right you're trying to promise so if I if I log if I log some sync func protect it right maybe you can get it something fun like this just log it simply it's probably then tell me that it's a promise a promise and apparently it was resolved of course there was nothing returned or anything so in its opinion it was resolved so here mmm for to work like a promise let's do our network request right let's do like response equals the fetch the API URL which again returns a promise so if it returns a promise in front we can write a waits and so we we await for the result and if it's a and if it returns a promise then we'll get the response here instead of dry having to write dot then and then getting the promise so the moment we get the promise well we also want now to get the data from that response and the data is in the response chasing which also returns a promise so we have to write the word a way to confront it's a synchronous or promises a synchronous so anything a synchronous you can write the word await in front but this moment we have the data that we want and we can just simply return the data and here since we know in the sync method returned response and if we're not in in a synchronous function and like for example for in the global scope of the in JavaScript if we're in the global scope min node or JavaScript doesn't matter well we're not in a synchronous environment so we actually have to revert to the dot then and have the data and then we can just control plug the data and here a which should work exactly the same boom again we have our image of the dog we wanted to get back so this is a sink weight and once you've understood that that when you have something with the sink keyword in front you can actually use a weight it's all good and a synchronous always returns a promise well I promise that then and we can get the data that was returned here that's all there is to it so we've understood a sink oh wait and now let's look at generator functions so the question is we already like maybe some of you know what a generator function is they're not I wouldn't say they are used too often just how they are but they can be used for fetch for fetches here I could just simply write a generator function I'm gonna call it Jen and it has to have that special star keyword somewhere after member I think it's here yeah I think it's there so I have my generator function and inside I could write yield that's a keyword one and if I call I create my iterator a generator function actually creates an iterator and I can do until vlog iterator got next to retrieve the value and what yield does is yield actually returns the the the value that's after it so one would be the value so if I if I did iterator dot next it would stop it yield and it would return one and here we can look at the console and we should be the value one well and their tax returns an object where the value is 1 so I don't have to audit value here afterwards mmm to actually get the 1 so here and then we could have multiple yields we could have like yield u 1 u 2 u 3 and for each next value it's always going to turn the next fad yield value that is awaited and I could write this three times in a row for example and we're in 1 2 3 because the the next is gonna call the the first yield available it's gonna go into the function when it arrives to yield it's gonna return that value and it's gonna save that position then when we come back into a next neck of the next it's gonna continue starting off where it left off and it's going to continue its gonna return 2 and so on and so forth and if we continue more we'll see that the value will be undefined but then it also has the object as we saw previously here it has a done if it's the values undefined it returns done true and we know that there's nothing left to get from this function from this generator function so this is actually interesting so question is how can we use this to our advantage to create maybe some kind of fetch requests in the same manner as we did here with a sink of weight what's totally possible because there are projects that exist for this for example um I believe it's called I think it's called flow and I think this one is called Co hmm actually maybe look it up real quick okay yes yeah it's called the Co and the idea is you wrap with the cofunction you wrap you wrap a use a generator generator function call back and you kind of use it the same way as you would with a sink await and the question is how do they do this you know without using a library could we implement this ourselves and the question the answer is absolutely and it's actually not that complicated so if you wanted to create if you wanted to create flow Orko and some general same manner and what we'd have to do is the following then you delete all this and I call it generator yield and do this we'd have to create for example what's going to we're going to name it flow and it's going to take in some kind of generator function all right in college in musicology and inside the flow we're gonna have to do is we're gonna have to get the iterator again with the iterator I'll call iterator imitator over here and then we're going to do is we're going to do return I'm gonna call it we create some kind of anonymous a synchronous this is really put a synchronous function it's gonna auto call itself this is this will auto call it and inside what we need to do is we need to define a few objects so elect OBG and the result that's going to be returned it's going to be equal to iterator next now while obj dot done is equal to false so remember it returns the object X returns undefined while it's equal to false only but what we'll be doing is we're gonna keep on well the first thing we need to is check if the obj value is actually equal to own own is an instance of the promise because remember we if we think this if we think of this thing as of like in a generator we would have to write like yield here and so yield always returns the value that's afterwards and this would return a promise this would return a promise so we actually want to handle the promises yes hmm so if it's actually equal to a promise because yield doesn't actually like like unwrap a promise and get the value we have to do that ourselves in this a synchronous function so to actually get it to work like like a single way we actually have to you you actually have to wrap it in some kind of a synchronous functions was actually exactly what we're doing here so at this point we would have to be like we're gonna re-up date and then the value you're saying await obj dot value and at that moment what we're gonna do is we're going to save you can save that updated object into res why well simply because remember we're gonna keep looping until the value is undefined well if obj is now undefined what we kind of just lost the results or the value that we actually want to return so all right obj iterator got next okay that value and the whole point of passing obj dot value here is for example this pretend this is some kind of a generator function and we write yield here and yield here well we get we get the response we get the promise from the fetch and there's a yield so we leave it and then we'd be in in our flow function we write dot next and we come back in and we pick up here right and then we type to do response Jason well it never actually gave the value returned here and put it in a response so this is undefined and we get an error so to actually update response with its actual value excuse me with its actual value then we need to pass that value in the next and it will simply update the response and we can you be kid here then do response Jason this is exactly what we're doing here and very end what we do is we do return there's dock value right and so let's try it out so we created our flow with the generator and sound we're going to simply do the resolves equals and we can see if that works it should return a promise so that's interesting so we can be flow past our generator function in here and what do we want to do we want to do we want to get the we do we don't respond you want to do fetch of the API URL and then we want to get the data by doing a response of that jason and then we just want to return the data there's to see out of this works of course you have to use the keyword yield just like if it was a wait and let's see if we can actually get the data and by just doing a result dot then I think I've seen everything thanks for watching the video like comment subscribe if you wish if you want me to talk about anything in specific or talk about any other subject just leave a comment and thank you again for watching [Music] you
Info
Channel: kemicofa
Views: 1,072
Rating: 5 out of 5
Keywords: javascript, closures, promises, async/await, generators
Id: JzsuEvH0-OA
Channel Id: undefined
Length: 22min 16sec (1336 seconds)
Published: Wed Nov 21 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.