Asynchronous JavaScript in ~10 Minutes - Callbacks, Promises, and Async/Await

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
asynchronous javascript callbacks promises async await huh this was one of the most difficult concepts for me to learn in javascript but don't worry because we'll break it all down in about 10 minutes all right first off if you're new to the channel welcome my name is jamesquick and every week i do one to two and sometimes three videos on web development including topics like asynchronous javascript which i am really excited about because asynchronous javascript learning how how and why javascript is asynchronous and how to work with it is one of the most important concepts you can learn in javascript specifically it makes javascript as a language a little bit more unique in comparison to other languages and it really is just core to how javascript works and the javascript that you will be writing in your day-to-day so there's three different categories commonly of asynchronous javascript we'll start off with callbacks we'll talk about those then we'll get into promises and we'll talk about those and then we'll talk about async await which is a newer feature in javascript that really kind of streamlines the process of writing asynchronous code and is my personal preferred way to write asynchronous javascript so make sure you stick around to the end to know how to write javascript asynchronous javascript in the latest and greatest and my favorite way so let's go ahead and get started and i've got lots of different callouts in here for different things we're going to do let's start with the idea of a callback and an example of this is one we've probably seen many times it's where we can do a set timeout for example and a set timeout will take a callback function and you've probably heard that term in that sense before and in this case what we're saying is we're calling timeout we're passing it this function which will log out waited for one second and we're telling it how long to wait before it does that which is in this case one second which is a thousand milliseconds so we save this and after about a second we should see that message come up now this is asynchronous because we tell it hey in the future javascript lan node call this function after the appropriate amount of time that's why that is java or that's why that is asynchronous it's also javascript so i want to give you a little bit deeper of an example here where you can have nested set timeouts and this gets uh into an example of demonstrating the callback hell that you can get into and you get into this kind of like christmas tree pattern but you have a callback function here and that thing is waiting a second and then logging out three and then inside of that you call a function that then takes a callback function inside of that one you then have a callback function so this is callback hell where you're nesting and nesting and nesting this stuff and this will do maybe what you expect where it'll do wait a second then do three two one and then you're on so those are your traditional callbacks are a traditional kind of simple examples you could also have something like this where if let's say we had a button in browser javascript and we called button.addeventlistener and we listened for the click event and then passed it a callback function and this is another example of a callback where we register for this event and then our handler the callback here is this part here now this code is running in node so i don't have access to the dom and dom element so i'll get rid of this just wanted to show you that that's another example a common example of callbacks in javascript let me comment this one out so now let's talk about the idea of an error first callback this is where all the code that we've run so far in those callbacks there's not really much of a chance for anything to go wrong but what if it does so let's do an fs.read file and i've imported the fs module up here as well as a node fetch we'll talk about that in a minute and the fs module is the file system module inside of node so in this case we're wanting to read a file so let's do an fs read file we'll tell it which file we want to read we'll tell it what kind of encoding we want to convert it to which in this case is utf-8 and then we'll have a callback that takes two properties an error property as the first one or parameters error as the first one and then data as the second one and the reason is you might fail to actually read this file so if we just start with logging out data and it's done correctly you can see it has the text here from that text file and hey this is an awesome video that's cool but what if something goes wrong what if we type in test.2 well it's saying undefined here because there is no data because an error happened so a traditional way that you'll see a lot of this code is something like this and i'll just kind of paste in this example where you first check for an error so if there is an error property log that out and then do whatever you want otherwise you can assume the data is good so in this case it logs out the data and then if we uh through an error here it will handle that thing and then log it out with this log here and again it's throwing an error because this is a file that doesn't exist all right so that's the idea of an error first callback and that's really important when we get into promises and async await is these things that are asynchronous sometimes things go wrong and we need to be prepared to handle those errors all right now let's talk about promises which is kind of like the evolution of the idea of callbacks and i want to start by creating a promise so by creating a promise you're passing it a function that accepts both a resolve and a reject callback basically and then in your code you want to detect whether or not this thing is successful or it failed and then if it's successful you call resolve if it rejects if it fails you call reject and so i'm going to take a little bit of snippet here to get a random number that is either a zero or a one and then i'll say if the random number is zero i'm going to consider that to be a good thing so i'll call resolve else i'll call reject so again promises always have a success path and a fail path referred to in this case as resolve and reject and then we'll see what that becomes when we use a promise in a second so since we have this promise we can call the dot then and dot then will take a callback function where we can log something like success and we'll save this and we'll refresh and we start by saying that there was an unhandled promise rejection so let's save again then we see success and success and unhandled promise exception the reason is that when we use this promise remember it can resolve or reject the the dot then in this case passing this handler to the dot then is only handling the success case if we want to handle the bad case the error case it's a dot catch and then we can do a callback function here with a console error of something went wrong all right so now we say this say this you see something went wrong and then something went wrong and then success so we're handling both of those so we create a promise with a function that takes in resolve and reject and then based on the action that goes inside of this function you or the promise itself will decide whether or not that's actually successful or not all right so that is us creating a promise but what if we just wanted to use an existing promise well we can use in the fs modules there is a promises set of functions where we can call read file in the same way we just did all right so this would be doing fs.promises and then calling read file the exact same way that we just did and now instead of using callbacks we can handle the dot then and the dot catch and you'll notice uh often you see uh these returned on a new line for readability and that's a really good habit to get into so if this success successful we'll get the data back and we can log that out or there is a dot catch for an error and then we can air that out all right so there's our text if it passes and then if it fails if we did a test.2 now you see that this thing is handling the error so this little snippet up here is how we do read files with promises versus this one up here and you can tell that this is a little less code that we're having to write with promises so this is kind of an upgrade here now another good example of promises is with the fetch api and fetch api is how we make xhr requests to a server and a good fun example of that that i like is using the pokemon api so you can call the pokemon api and you can get some information about a pokemon back so if we want to use that inside of node there's a node fetch package that i have installed so that we can do fetch the same way we would inside of browser javascript so we'll paste in that url and then just like what we just saw we can actually copy this you can see that that promises will follow a pretty similar format well we'll have a success case which is in the dot then and then we'll have the uh not success case which is in the catch so you can see this is successful it gives us back lots of information about our response but it's not quite actually the data that we're looking for so actually what happens is this gives us back a response and then what we want to do is get the json out of that response and getting the json out of that response happens to return a promise which means we can then chain on another thing here where we're going to get the actual data so then we'll log out the data and we should see that that comes back with abilities and name and url so let's take a second to break this down again we call fetch we handle the success case with dot then we get the response which is just the raw response that comes back and then we need to convert that thing to json so res.json returns a promise then we can chain on a promise dot then to handle that promise and then we get the actual data and we log it if this were to be bad it would trigger our catch so you can see if we typed in something like undefined you can see that that is going to throw an error it says invalid json but we're able to handle that inside of our catch all right so now i want to show you the evolution of promises to async await this is my favorite way to write asynchronous javascript this is the way that i always do this so i'm going to copy in a snippet here this is going to be an updated snippet of our load file work that we've done in the past all right so this is going to be an updated snippet of the read file so this is going to be an updated snippet of the read file stuff that we've done a few times now all right so now in this case what we're doing is we're defining a load file function and the reason is if we want to use this async await capability we have to mark a function as async so this is looks like a regular arrow function except we add the async keyword so now this is an asynchronous function which means inside of this we can use the await keyword so what will happen is we'll call our fs promises read file the same way we did before but instead of passing callbacks or doing a dot then to handle the responses we add the await keyword and we get our data right here that's really cool this is much more streamlined and a lot more readable for me especially or this is my preference in terms of readability so now if we save this uh we'll get this is an awesome video so we see that response coming back again so all that is working but the problem is what if we do an error here what if we do test.2 well that actually throws an error and that's where we take this one step further where we have a try catch and so what a try catch is saying it's like hey let's go ahead and try to run some code which will be this code here if some sort of error happens now we can handle that error inside of this catch this way so we'll log this thing out in this case what this should do is it should safely handle this response log out the air but we're still able to use our async await functionality again i love async await this is code that i write all the time inside of my personal javascript code all right so let's take this uh one last up further and i'm gonna copy in the fetch pokemon example so here's our new fetch pokemon function and it will make a fetch request the same way we saw before except it's awaiting that response getting the response here and then it's awaiting the res.json remember that this res.json returned a promise before so now we can await that response the same way we do the original fetch request so we make the request we await the response we take the response we convert it to json and we await that and then we end up getting our data so in this case i'm passing in an id of a pokemon and then making that request we should see that we get information coming back but what if we pass in nothing which would then make this id undefined and throw an error we're not handling it and you'll see that we get an unhandled promise exception here which means that we need to go and handle this with our try catch so the same way we did this before here's our try this is the code that we want to try and then we'll catch an error and then error that error out if there is one so now you can see that it throws that or it logs out or errors out that error appropriately just like we did with our read file but now this is the type of asynchronous javascript that i prefer to use i love using async await myself i use async weight in every instance that i can i almost never use callbacks if i can avoid it and there are some things that you can do to kind of convert older callbacks to promises so you can look that up or if you're interested in knowing how to do that let me know in the comments but i will always use async await in my javascript i'm curious if you've seen these different formats for doing asynchronous javascript what is your favorite callbacks promises async await let me know in the comments which one of those you prefer hopefully you enjoyed a lot in this video about a cool challenging topic in asynchronous javascript and i'll see you in the next video
Info
Channel: James Q Quick
Views: 69,998
Rating: 4.9553905 out of 5
Keywords: async javascript, asynchronous javascript, javascript callbacks, javascript promises, async await javascript, javascript tutorial, async await, javascript promises tutorial, async js tutorial, async await js, web development, programming tutorial, how to use promises javascript, es8 javascript, web development for beginners, javascript tutorial for beginners, javascript tutorial 2020, asynchronous javascript for beginners, javascript promises explained
Id: 670f71LTWpM
Channel Id: undefined
Length: 13min 55sec (835 seconds)
Published: Tue Dec 08 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.