async / await in JavaScript - What, Why and How - Fun Fun Function

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

I love me some mpj. Great video!

👍︎︎ 1 👤︎︎ u/Zwooosh 📅︎︎ Sep 03 2017 🗫︎ replies

I like you style! Very exciting!

👍︎︎ 1 👤︎︎ u/AlternativeNickname 📅︎︎ Sep 04 2017 🗫︎ replies
Captions
good morning today we are going to look at the asynch await keywords which allows us to pause the execution of functions and this in turn allows us to write asynchronous code that reads like synchronous code I am npj and you are watching some fun function [Music] [Music] [Music] I am wearing a blazer today because sometimes you just feel special let's begin I am going to show you some code written with plain promises we are going to do some fetch this is built into browsers but it doesn't exist in a node so we are going to install a node module require little node fetch I think it's called I cannot find module no - now that's correct because doesn't exist yet however using quokka we are which is the in line evaluation thing I'm using I'm going to install the missing package for only this quark file hang on and on screen so now we can start to define a function so what we're doing here is a function in a fictitious a cat API app system so this is going to get the Earl of the profile image of a user let's call it so that we see what is happening as we go along so as you see the call is evaluating to undefined nothing no surprises there but let's start coding it alright so as you see here we get some garble here and it that is because search is returning a promise which will eventually evaluate resolve I mean to a response so we'll call them on the promise and we will pass it a function that will take the resolved response and we will call dot jason on it not unsurprisingly this parses the response at Jason so now we see that result is a promise that resolves into this this Jason thingy here but we don't want all this we are just interested in the image URI here so we are going to call this on the promise and then we are going to call data and we are interested in the image Earl fantastic the result of such avatar Earl is now a promise that resolves to the image your eye of the user warning if you are unfamiliar with promises this video is going to confuse the hell out of you so if that's the case you should watch my promise video first you can find it here or in the epital description I am now going to attempt a rewrite of this function using a things away well I'm going to comment out the initial implementation yes so that we can keep it in mind while we're doing this the first thing that we're going to do is to make this function a synchronous you can notice down here by the way that this now returns a promise that resolves to undefined we're going to talk about this a little bit later okay let's begin by creating an intermediate variable here called data and I'm going to grab this from the previous implementation and paste here and let's just see what data is at the moment okay so as we see here it valuates to a response so this is a bit bit misleading we are looking for the response at the moment I would can't see it here because it crops it but this is actually not a response this is a promise that resolves into a response so I'm going to write a keyword here called a wait and this means that there is this is now the actual response object this is not a promise that that resolves to a response this is the actual response because the function has has paused here and then resumed once fetch has arrived and then resolved to the actual response object so let me continue here to actually demonstrate this to you I'm going to write data here and I'm going to do response dot Jason and I'm going to also evaluate data here so as you see here data is now a promise that resolves to the parsed JSON data so we would not be able to do this here unless this was the actual response otherwise if it had been a promise we would have to do then response yadda yadda and then response dot dot dot JSON but we don't need to do that because this is the actual response object however data let me write that out so that it come on yeah that data still evaluate it's still a promise that resolves to the to the parse JSON data so I need to write a wait in front of this as well and boom now you see that it's no longer promise it's the actual actual actual data so see there I remove their wait and it's a promise but if I add the wait it's now the actual data let me delete the response line here we don't care about that in moment because now we know what the data and I'm now going to do data dot a image Earle and we're going to return that oh and now we see that the result of fetch avatar Earle is now a promise that resolves to fetch avatar arrow and thus it behaves exactly like our previous implementation here so now we have rewritten it using a sync wait start I'm going to read you a description of what a sinker weight is I will repeat it at the end of this episode and by then you will hopefully understand it inside a function marked as a sync you are allowed to place the await keyword in front of an expression that returns a promise when you do the execution of a sync function is paused until the promise is resolved you got that if you did well then why are you watching this video go out and look at nature instead on the other hand if you're confused excellent keep on washing the idea behind the asynch await keywords is to be able to write asynchronous code that flows like synchronous code okay so nothing really let's go back and look at our previous code looking at these two and it's not completely obvious that this flows in any different way from the promised example let's examine an example where we have a little bit more nesting so remember this is a cat api and all of the users are cat owners and imagine that we want to fetch the profile images of all the cats that a user robes so this function will begin just like the previous ones we will fetch a user and we will pass their JSON data [Music] okay so we see here that the user has this array of cats but the cats are not actual cat data it is Cat Cat IDs so we need to fetch these cats we iterate over the cats or rather we map over them let's say we want for every cat mm-hmm how does the cat all right the cat our IDs so there are not really cats so let's write cat ID because other otherwise we'll be confused let's fetch that cat what oh hang on I'm doing this wrong ah we need the cat and we need the cat ID all right now we're getting somewhere they are at Hertz in one cat sniffles and it has some image URI let's return this image URI image cool and we need to remove the curly brackets okay we still have an undefined over here ah it's okay we're not returning the result of our fetch here let's return that still nothing why not okay we're not returning the results of our map let's return that okay that's better now we have something it's an array of promises that is not particularly useful because we want the actual resolved values here not the healthy promises so what what has happened here is that map has went over the cats and for every cat it has transformed that cat into a promise of a cat URI so um let's put this into an immediate intermediate variable first I will remove this line here and I'm going to remove these curly brackets because we don't need them and we don't need the return statement let me just see what promises are cool still this array of unresolved promises return so instead we want to return a promise that resolves to an array where all these promises have been resolved and to do that there is a handy function in JavaScript code promise all look you can pass an array promises boom come on there you go let me delete that line because it's just confusing us and now we see that it's indeed an array of images that contains cat avatars also by the way if you are not familiar with map this probably confused you of it luckily I do have a video on map over here and you can also find it in the episode description what we are going to do next is to rewrite the code that we just saw using a sink and weight but before I do I would like to take a break and make an announcement that is way overdue some of you know this but most don't I have quit my job at Spotify and unfun function is now very officially my part-time job Oh this week on Friday on Friday morning I'm going to release a video where I talk about the launch of a patreon for fun fun function and more importantly I'm also going to talk about the launch of Fun Fun forum I'm really really excited about this and in that video I will be talking more about what fun fun forum is but the important thing the important thing that you need to have in mind is that if you become a patron this month August lastly is the 31st you will get next to your name a special forum badge a permanent special badge that for eternity shows you that you were one of the first patrons of fun fun function after August 30 first nobody will get these badges ever it will be a very very ugly badge that I will probably have hand drawn with a pen it will absolutely positively not be worth your money so for the love of God only do it if you want to support funds on functions and if you want a special forever for a maternity batch of infinite value back to the ordinary scheduled programming where were we okay let's rewrite this function using I think away [Music] [Applause] [Music] [Music] all right so let's walk through this one first it uses a wait here to wait until we have the data and then it parses JSON waits for that and then when we have the use of data it construct a an empty array of cat image your eyes to hold them and then starts looping the cats array of the user and for every cat ID it's going to do a fetch and then let's go to wait for that fetch to complete and which results into Eris bowls which is then calls JSON on it waits for that to resolve into the actual cat data and then it takes the image your eye on the cat data and pushes that to the cat image your eyes and it does that for every cat and then it returns the cat image your eyes and that is what we see here in the result again you don't see it here because it's it's uh it's cropped here but this is not the actual result this is the promise of a over result that eventually resolves into the result the first thing that strikes me when I look at this code is there's a be in here what strikes me when I compare the asynch await example with the promised example is that the SN Kuwait example is a lot less straightforward which ironically wrote not straight the code here it flows in a very human readable manner at least to me the second thing that you should notice is that they are not logically equivalent if you notice that it means you have eyes good job eyes the sink await example it will load the cats in sequence while the promised example will load them in parallel so the promised example here is a lot lot faster I wrote it like this because I want to demonstrate that I wait only were for single promises it cannot wait for multiple promises initially when I was exposed to a sinker weight I felt that it was a little bit useless how do I put this okay I could totally see how I think a weight was useful for simple scenarios and how it could make the code flow in a more approachable manner but at the same time it wasn't as flexible as raw promises so it just felt like a bad deal to me but I came around eventually because I realized that you can just fall back to raw promises when a sinker weight limits you and I'm going to do that here I'm going to delete this comparison comment and I'm going to actually comment out this bit here okay let's write [Music] tre wrote the code have good at the code by the way I wrote that from a script I don't actually I didn't make that up on the spot yes sir you know alright so what do you see here is promises are raw promises and a sink weight mixed a little bit together this code is going to be a little bit confusing if you are new to a single weight so I I recommend that you at this point post video a little bit and look at this code and try to get familiar with what is happening before continuing okay freeze frame okay so what probably was the most challenging part of this thing to graph is that we are passing and a sync function to Matt we can do this because as I briefly mentioned before ah I think functions return a promise when you called it let's look at a much simpler case to examine that and go to a point Thank You killing and coding sorry joking it's below people can again be later will be no chronicler of the booth and our sync function will always return a promise which makes sense because it's a synchronous but let's go back to where we were before let me delete this because it's mostly just distracting in this example we have mixed a raw promises into our await example because we want to fetch things in parallel but for a minute I want us to like think in the other direction what if we didn't want things to happen in parallel what if we had a case where we wanted things to happen in sequence let's imagine that we have a batch script that processes a few hundred thousand users and our imaginary that script looks like this has a sequel query it does this database query it gets a promise get some users and then it loops through the users and then for every user it processes the user and it awaits for every process to to complete a real resolve before it continues so process user you have to imagine that that returns the promise so in this case we have a lot of users so we don't want to create a hundred thousand requests at the same time so in this case it makes for this simple case we just want to do this are sequentially here a weight makes a lot of sense we can absolutely do this with promises but I imagine that it will be a bit awkward I shall attempt to rewrite this using promises in the last example we actually had a fake real service with real data real fake data but in this case this is just imaginary so you're not going to see any correct in line evaluation going on here it's your scan DUI refactoring [Music] [Music] boom functional programming reduced what do you think this compared to this to be honest I don't think it's this is less bad than I anticipated it to be to be honest I think it's really a testament to the flexibility of reduce but it is still very clear that the I think a weight example is just a lot nicer let's summarize first we looked at what a think a weight is inside the function marks as a slinked your life to place me a waste keyword in front of an expression that returns a promise when you do the execution of the sinc function is post until the promise is resolved we then talked about why a sinker weight excess and the idea with the singer weight is to be able to write a synchronous code that flows sort of like synchronous code and then we spend some time looking at how to actually use it so did I explain this well enough did you understand it is unclear that's cool you're supposed to comment down below if it is clear to you then please help someone else out teaching is the best way to learn remember there's a patreon video launches on Friday morning so if you want please do become a patron you have just watched an episode of fun fun function I really sees every Monday morning Oh 800 GMT if you don't want to wait for the next episode you can watch this episode right now that the AI overlords have selected totally with your best interest in mind I am mpj until Friday morning thank you
Info
Channel: Fun Fun Function
Views: 236,349
Rating: undefined out of 5
Keywords: programming, coding, javascript, computer science, software engineering, software, functional programming
Id: 568g8hxJJp4
Channel Id: undefined
Length: 23min 59sec (1439 seconds)
Published: Mon Aug 14 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.