Async + Await in JavaScript, talk from Wes Bos

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
yeah [Music] everyone thanks so much for coming out today my name is Wes vos I come all the way from Canada I did actually grow up learning French so if you want to try to talk to me in some french-canadian I might be able to understand here today I'm going to talk to you about a sink await and the reason why I want to talk to you about yes thank you somebody laughed at that joke can we just take a second to appreciate my hilarious joke thank you thank you I want to talk to you about a sink away today because flow control in JavaScript it's really hard so how many of you show of hands how many of you are using promises in your code date today right now okay cool quite a bit I'm gonna go go quick review through promises just because this is the foundation of a sink away promises in JavaScript are sort of like an IOU for something that's going to happen at some point in the future so this could be an ajax call returning data this could be accessing a user's web cam once they hit the allow button on the little pop-up that shows it could be resizing an image the point is that all of these things take time and with promises we simply kick off the process and then we move along with our lives we only come back to that thing when we need to to deal with the data so but why do we do it this way in JavaScript and that's because JavaScript JavaScript waits for nobody it's simply everything in JavaScript is a synchronous meaning that we kick off the process and we come back to it when we have to deal with the data or deal with the response so let's relate this to real life something that maybe you did this morning which you you want to make coffee you want to drink your coffee you want to cook your breakfast and you want to eat breakfast would it make sense to finish making coffee before you can even start cooking your breakfast would it make sense to make the coffee drink the coffee and then once you're done then you can go ahead and and start making your breakfast no that doesn't make sense we want to really just kick off the process of making coffee and then come back to it and deal with the result accordingly so how we sort of dealt with this in the past is something called Christmas tree callback Al and we would write code that looks like this we've all written terrible terrible code that may probably got a little bit more it looks like a Christmas tree if you go on the side what's really cool about that is the promises allow us to start writing code like this where we can run our functions make coffee make breakfast and they return a promise not the data a promise that the data will come at some point in time and then we can use dot then to listen for the data actually coming back we can take it one step further and sort of wrap it in a mega promise by saying promise dot all and that will allow us to wait until both of those things are done until we go forward and deal with the result in this case eat our breakfast and drink our coffee another example let's say we were building a little animation library where we want to do one thing after another well rather than doing the callback hell on the table what we can do is kick off move to which will return a promise and then we can chain our dot vens whereby returning a promise from each subsequent one so this is really exciting because a lot of the new browser api's are being built on promises so we've got fetch or you can fetch your data then that will come back we convert it into JSON and then finally deal with that data at the end of the day we can use a library called Axios which is really exciting where it has some it's like kind of like fetch but it has some really good built-in defaults where we don't have to have that second and then chained although on the one there's many many more browser api's payment requests dealing with credit card data in the browser getusermedia getting access to the web cam web animation api all of these things are being built on standard promises it's really easy to make your own with promises as well so here we have a function called sleep where it takes in the amount and the way I promise works is immediately you return a promise and then what you do inside of that promise is you either resolve it when things went well or you reject it when things didn't go well so in this case after 500 milliseconds we're going to resolve it with some data or if it's less than 300 milliseconds I'm going to reject it because that's too fast and what that will allow us to do is a little bit something like this where we can write our code and then we can chain and then then on it and by returning a new promise from each one we're allowed to keep going and chaining that code along the way look at it promises are really really great but the then I'm not happy with it right it's still kind of callback II and any code that needs to come after the final promise it all still needs to go into that final dot then it can't just be top level in your current function this is where a sync awake comes in is sort of saves the day a sync oh wait is still based on promises but it's just a really nice new syntax for working with it so we looked at this example earlier we went from callback to promise based well what we can do now if you look at the bottom here is we can simply make a function by tagging with a sync and then inside of that we simply put the awake keyword in front of each of those functions and that will simply sort of pause the function from running it will wait until that promise resolves until it moves on to the next line of code no thenns no callbacks needed so let's break it down javascript is almost entirely a synchronous non-blocking we talked about that is great that we can create these experiences without having to lock up the browser whenever we do anything but it's hard to read it's sort of hard to author this code so if we look at PHP if we're not using any threads or anything we wanted to go ahead and fetch two things from github what we would do is we would fetch the first one and when that comes back we would fetch the second one and then when that comes back we have both pieces of data and we can go ahead and use them reads really nice top to bottom not so great because why am I waiting for Wes to come back before I go off and fetch the Scott in JavaScript what we can do is we can put both of those promises into variables and then wait until both of them come back they can both fire off one after another and then we can wait for both of them come back and then we can use the data by creating some HTML and displaying it on the page so the PHP is kind of easier to read but the JavaScript is more performant because we're not like waiting on unnecessary things to finish but I'm not really happy with either so a sink away gives us synchronous looking code without the downside to actually writing synchronous code so how does it work first thing we need to do is mark our function as a sink so you still keep your regular promise functions nothing changes with your functions that we return a promise what we do now is we create an a sync function by writing the word a sink in front of it then when you're inside of an a sync function you simply just await things inside of it so you can either just await the sleep function and that will just wait until it the promise resolves or if you care about what's coming back from that promise maybe it's some data from an API then we can store that in a variable so really it's it's the best of both worlds let's take a look at another example here so in this case I'm sticking it into a variable and that's another way that we can write it and here I'm doing the PHP thing where I await Axios yet and then when that comes back I'm going to await the second Axio second that's kind of slow we don't want to do that right so what we can do is we can simply await promise dot all and by passing promise that all our other two promises we sort of make one big mega promise that we can await for both of them to finish so one takes one second one takes two seconds it's going to wait the full two seconds before we go on to the next line of code now that's great but if you've ever seen any examples online the error handling starts to ugly it up so let's look at a couple options that we can use for actually working with error handling first option for error handling is just don't write bad code and you don't have to handle errors I'm joking guys don't actually do that you always have to handle your actual errors really the first option is and this is probably likely what you have seen online if you're looking at any examples it's use a try/catch so just wrap everything in a try-catch and you're gonna be nice and safe and the way that that looks is you have your sync function you give yourself a try write all your code inside the try and then if anything happens inside of that try you catch the error in your catch and you deal with it accordingly second or third option is a higher-order function where which is kind of cool because you can chain a dot catch on a sinc functions so this is a little bit more complicated you might have to come back to these slides and look at it but let's walk through an example so I've got a function Yolo where I don't care about error handling in this function I'm gonna assume everything works great then I'm going to await something that maybe gives me a 404 and is going to break because no data came back this could be a syntax error this could be any error that Axios might throw you then this is where it gets a little bit hairy so stay with me will you create a high order function called handle error that takes as an argument the actual function and then from that you return a new function so you basically just return the same function but with a catch tagged on to the end and the catch that's tagged on to the end that's where you actually handle your error if you're a hotshot and you're using es6 for absolutely everything you can do it in one line and then tweet about how cool you are but I still don't understand exactly how all of that works so the way it actually works right we created our one function that had no error handling and then we created this weird high order function that takes in the function and returns a new one then what you do is you just pass your unsafe function to handle error and that will sort of create the new function that still does the same thing but it's now a little bit safer and able to actually handle any errors that might happen inside of that function and this is I've myself I find this extremely handy in note and Express how many of you write Express Apps hands up okay probably about half of you so let's say we've got an orders page and when you hit the orders page we want to find the how are the orders for the user right so if there were no orders let's let's throw an error but this could be any type of error syntax or whatever now normally in Express you need to call next and pass the error too next right but and then what would happen is that route would not render it would pass it along your middleware line and then at the bottom of your middleware Express would render out an error page with the subsequent error code and error message but that's good but it doesn't really cover errors that we throw you have to explicitly call next for that to work it doesn't handle unexpected errors or syntax errors or database connection errors or anything else that has happened along the line of your middleware so what we need to do here is we need to catch all of our errors and pass them along to the next function we want to pass any error and pass it along to the next function so this is where our higher-order function comes in so I'm going to create another one of those weird functions that takes in the function and returns a new one but in this case I'm just going to return the regular request response next function and chain a dot catch onto the end and the dot catch all it does is calls next with the with the error that gets put along to it again if you're a hotshot there's an error there's one there you can do in an arrow function now this is how we implement it we've got our catch errors function then we write all of our routes or all of our controller functions without any error handling in it and then you can take your controller get orders and pass it to catch errors and that's really really nice because you can write all of your routes without having to worry about specifically handling the error in the exact same way and then you can just wrap each of your routes in this catch errors function the fourth option is handle the error when you call it so sometimes you do want to handle the error when you call it because you say oh this is a special case if there's an error here I need to handle it in a different way so it's pretty simple you make your a sync function called load data and maybe an error happens and that when you call it you can just chain a dot catch on to the end and then deal with the error however it is that you'd like to do that fifth option this is really important if you're writing node node will soon exit the process if your promise is rejected meaning that if you have any code that doesn't handle an error on a promise the entire process will exit and then that could mean your app actually goes down so pretty simple you just listen for the unhandled rejection event and then when that happens you can deal with it accordingly probably send it off to some sort of error handling service so that you can log it and deal with it in your in your code so I'm really really excited about a sync oh wait I was excited about promises but now that a single wait has come around it's it's been a while since something fundamentally changed the way that I owed my JavaScript and I code my flow control I was using a cinco cinco de ask the library for a long long time which still has a lot of really good use cases but a lot of my regular flow control has moved over to using a sync away so here's a couple tips for starting today first write your api is in promises so i know that we can't go and change all of our existing code that is likely callback based or maybe you used another promise library but you can write your new api's in promises and you can resolve and reject from them use a sink a wait for flow control as we've shown you today convert older api's with promise a PHY so there's a bunch of different libraries out there and node even now ships with something on the U tillage which will allow you to take any standard call back based function where the error comes first in the callback comes second you can just convert that to return a promise rather than having a call back and that's really nice because if you're dealing with any older API where you're doing less a library that's called back base you can still use it with a sink oh wait finally choose an error handling strategy take a look at the ones that I've explained here you'll probably need one or two of them for your actual application and and implement them into your actual application so I want to encourage you give a sink a wait a shot I'm really excited about it I think that's really going to change that the way that you build your application thank you so much [Applause] [Music] [Applause] [Music]
Info
Channel: freeCodeCamp.org
Views: 87,948
Rating: 4.9534883 out of 5
Keywords: learn to code, programming, coding, javascript, web development, web design, tutorial, python, android, security, testing, coding tutorial, javascript tutorial, web development tutorial, html, css, design, html tutorial, css tutorial, learn to program, learn how to code, learn how to program, get a programmer job, get a developer job, python tutorial, android tutorial, linux, learn programming, learn coding, linux tutorial, learn linux
Id: DwQJ_NPQWWo
Channel Id: undefined
Length: 15min 52sec (952 seconds)
Published: Mon Apr 16 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.