Tips For Using Async/Await in JavaScript

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in javascript it's much cleaner to use async await than it is to use promises with dot then and catch so in this video i'm going to show you how to go from this to this and give you some async await tips along the way all right so i'm starting off here in a code pin with an example using the fetch api in javascript and what this is going to do is make a request to this placeholder jsonplaceholder from typeycode where we get some dummy data back and this is just kind of a basic to do here and this is an example using uh dot then and dot catch so you can use callbacks you can use dot then dot catch and then we can also use async await which we'll look at in a second which i personally think is a lot cleaner so what we do here is we declare this url we then make the fetch request to that url and that whole thing returns a promise and then to get the data out of that promise we have to add a dot then to get the response and this response in this case is an http response that we need to convert to json or we need to get the body out of that response and convert it to json and we do that by calling res.json which in turn returns another promise now this is one of the neat things about using promises with dot then is you can then chain on another dot then so because this returns a promise res.json we can dot then again we can chain these together and then get the data so this is the actual data for that's coming back from this url and then if there's any errors we'll log those out under here by using the dot catch at the end now this does not look all that great to me all the dot bins in here are multiple dot bins then the dot catch down here it's just not how i would prefer to write my code async await is much cleaner so what we're going to do is we'll convert this over to async await so we'll get rid of everything in here except for the url and then we'll go ahead and convert this to an async await example so we have our url and then what we want to do is uh put all this inside of a function so we can say load data and then for async await to work we have to mark the function as async then inside of the function now we can use the keyword await inside of it so you have to mark your function as async to then be able to use the keyword await inside all right so it looks like that's just gonna is that just gonna wrap in a weird way there we go that might be a little bit better so we have our url then we have our fetch now instead of doing a dot then what we're going to do is await the response that comes back from fetch so a weight keyword here says like hey fetch request go ahead and do your thing i'll just sit back and relax i'll sit back and wait for you to return that back to me all right so we have the fetch request now how do we get the actual response well we can just assign this to a variable and call it res so then from here we can log out our res variable we can match all these up all right so now since we put this inside of a function we actually need to call this function so let's call load data and hopefully we get our response logging out over here so it's an object we'll need to go and look into that a little bit here so we're able to get the response from this request and if you remember there was another step that we needed to convert this thing to json and we had to do this nested.then callback function which is really really not great so let's uh let's try this again where we'll get the data and this is going to come from the res.json so there's a json function that we can call it also returns a promise so we need to await that response and then we can log out our data hopefully we'll see that show up over here in the console there we go so we're able to get our data this looks much cleaner than what we just saw so a couple of tips here your function must be marked as async and then you're able to use your await inside of here now you might be wondering since we have to mark this function as async can do we have to have it be inside of a function can we do this as a top level uh function the short answer is no and i'll show you how to fix that or how you can uh in a second if you want to but another tip here is that once we make these requests what if something goes wrong we need to handle those errors let's say for example i do uh do he he he or he he in front of this domain json placeholder it's going to actually throw an error that we're not handling so you see it's i guess in this case it's not actually showing us this data if we were in node you would see an error logged out here because we're not handling that error so uh the one thing we need to do to handle this is to wrap this in a try catch so we say hey let's try to do this thing let's try to do all three of these things and if not what are we going to do well we will catch that error and then we will log out that error all right let's move this data back up here so now let's see if we have that formatted correctly cool so that is able to make the request appropriately and then if i add hihihi in the domain here we should see that that is going to trigger the log of our error over here which it doesn't seem to be what if we mess with https there we go there okay so you see our previous error so that's coming through now so we're able to handle this error we're able to make two async requests or requests to things that return promises and get the data back directly by having this inline async or excuse me inline await inside of an ac function a sync function which is pretty neat now a couple things for you to know if you're using the the fetch api in javascript uh you should also be checking the console log you should be checking the res.status or res.ok res.ok will return a boolean if the status is between 200 and 209 so we should see that returns true if we were to point this to something that doesn't exist it's going to return a 404 which then means that res.ok is not okay it's going to return false so if you're using the fetch api and in any other apis that you might be working with make sure that you know how an error comes through because it may not actually trigger the dot catch down here it might be something that's embedded in the data so you might have to check that another little hot tip for you all right so another key to this is that async functions here now return a promise this may be you may think this is fairly straightforward but by default they return a promise so let's say we wanted to return the data that comes out of this and then we tried to log out the data actually let's do const data equals load data and then let's log out data so take a second pause really quickly to see what you think this is going to do it probably doesn't do exactly what you think because this function up here will return a promise so even though it's got async await even though we're returning the data here because it's marked as async this means that this function inherently returns a promise now if you handle that promise in theory we'll get this data here so if this thing returns a promise we would need to do a dot then here to get the data and then we can log this data here and then we can get rid of the variable assignment and let's see let's get rid of this log up here and let's make sure that our to-do's is actually pointing to a correct url and now let's see if we actually get back this data cool so because this function is marked as async it is now going to return a promise which means then to pun intended to handle or to get the response back we have to do a dot then since we're not inside of an actual function here now what if you wanted to do top level async await well you can do a little bit of a hacky thing called an iffy that is marked as a sync so an iffy allows you to define inside of these parentheses a function that will then be called directly so you're putting let's see if i the bracket yeah making sure i have my syntax right here if these are tricky and kind of gross to be honest so inside of this parenthesis i have a function that then is getting called immediately it's an immediately invoked function so that means in here i could call say const data equals load data and then await this data console log this data but there will be one more thing we're missing if we want to do this we need to mark this function as async so this will allow us now to use this iffy to run top level async await which means i don't have to put it inside of a function per se although we're kind of hacking it together to put it inside of this iffy function now one thing to note with node i believe it's 14.8 uh running top level async without this little hack running it like this is actually available in node 14.8 i think so you can go and double check that but in some depending on which version of node you may be able to use this directly and not have to do the kind of hacky iffy thing hacky iffy thing all right so let's i'm going to comment this out because i'm not going to use this anymore the last thing i want to show you is the idea of a promise.all now let's say that with this api we wanted to retrieve uh the first three items inside of um inside of the to do's that come back from this placeholder data well if we wanted to make three fetch requests it would be really gross and well actually let's just take a look at what that would look like so here is well this copy no okay so let's do this this let's do url two this will get item two this is three and this is three so this is again really gross for each one of these we would need to do all our both of these statements so we could uh duplicate this twice have this be one one two two three three you get why this is not so great this will be three this will be two this will be one so we're making the request for the first one we're getting it's data we're making the requests for the second one getting its data and so on and so on and then we could potentially return an array of these uh pieces of data so we could do data one data two and data three and if we were still logging this out i guess we could let's go ahead and let's leave this iffy and log out this data let's just see if we get those three different things in an array because we just wrote a little bit of code really quickly there so it says undefined we look inside of oh url1 there need to mark that all right let's see if that fixed it still undefined ah and we need to make sure that we update these response objects to res1 res 2 and res 3. all right now can we get back an array of data there we go okay so all that stuff is coming back which is good but this is obviously really gross so how could we um how could we change this up a little bit well we could uh use promise.all so promise.all is a way to kind of group promises and then let them run at the same time because the problem with async await here if we do this we're going to have to make these two a await or async request those will have to finish completely then we make these two then we make these two which means if it takes two seconds which it does if it takes one second for each to get each piece of this data so each of these to do's that means it's going to take a total of three seconds to get all of them back however with promise.all we can let them run in parallel so that we can run all three at the same time which means in theory the total uh the total time it takes to get all three would be just one second so we can now kind of group these things into one so we can say we can get our results and we can use promise.all and then now we want to pass in an array of our requests so the first one could be fetch euro one and then i'm going to copy this a couple of times so there's fetch for two and fetch four three probably be better if we put this on its own line all right uh and maybe even for readability for extra readability to put these on their own line as well all right so what we're saying here is we're gonna pass in an array of promises fetch returns of promise and then results here is going to do a promise.all on each of those so if we then were to log out the results we're not quite getting the data that we're looking for yet but we are getting what comes back from the actual uh there it is right there the actual uh fetch request we then need to convert that data to json all right so we can get all of or we can get the results back in an array where they're in order first second third and then we could also take those uh those items that come back in results and we could use those to convert them each to json so we could do this by taking the results we could map over them and then for each one we're going to convert it so we're going to say for each result we want to return result dot json all right so this is a little tricky but we're saying as we iterate through each one of these results we want to call its result.json if you remember result.json or response.json returns a promise so now this is actually the data responses array and we can then use that to get the final data is promise dot all and then we pass an array of promises which is data and actually i think this is supposed to have been named data promises let's name that a little bit better data promises all right now let's try to log out the final data and let's uh get rid of these returns let's start to clean this up a little bit let's see if that works all right so we've got some sort of error in here oh well the one thing we need to do is await the promise.all we completely missed that so with promise.all since it return it has to do some asynchronous stuff we have to then await to get its results after we get those results then we map through them to convert each one to json then we can await converting those each to json and now we get the the final data which is logged out and we could return the final data here and get rid of this log all right so what we're able to do just to do this one more time is we're able to make all three of these fetch requests in parallel at the same time get all three results those are in order in an array then we convert those results to json so this returns promises to get the data then we promised out all that and we could actually put this all in one line if we wanted to that maybe is a little grosser but that should work out the exact same there we go so that works out the exact same so what we're doing there is we're getting our array of promises from mapping each one each result to its json form and then a wait promise all lets all those three things run in parallel instead of after each other and then we get our final data and return that so a couple of different things to make sure that you remember when working with a single weight you have to mark your function as a sync that enables you to use the await keyword inside of it you cannot use unless you're using a specific version of node 14.8 or higher you cannot use async or weight or excuse me a weight um unless it's inside of a function so if you want to use top level of weight you can wrap it in this iffy thing which is kind of weird it's kind of gross and then lastly make sure you're handling your errors by wrapping all of your async stuff async weight stuff inside of a tri-catch so you handle errors and do it that way all right hopefully that helped you understand a little bit more about the details of how to use async await let me know if you have any other questions related to async await or asynchronous javascript i'd be happy to cover them in another video thanks as always for checking out this video and the channel and i'll catch you next time
Info
Channel: James Q Quick
Views: 357,567
Rating: undefined out of 5
Keywords: asynchronous javascript, async/await javascript, async await vs promises, how to write asynchronous javascript, javascript tutorial, async await, async javascript, javascript promises, web development, js promises vs async await, javascript fetch, top level await javascript, promise tutorial, javascript (programming language)
Id: _9vgd9XKlDQ
Channel Id: undefined
Length: 16min 26sec (986 seconds)
Published: Thu Jun 10 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.