Async Await vs. Promises - JavaScript Tutorial for beginners

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
async oh wait a single weight what is async weight why does it exist why do we need it and when should we use it this is episode 13 of a 10 part series called you know what let's make it 20. this is getting ridiculous 20 things JavaScript developers should know but probably don't this is episode 13 async await plus a bunch of updates and announcements at the end so stick around let's do it [Music] in episode 11 I showed you what asynchronous programming is versus synchronous we used callbacks to achieve async then in episode 12 we took that example and converted it into using promises in this episode we'll take the same example and convert it to use async awaits alongside promises if you haven't seen those two episodes first I recommend you do that then I'll show you a couple of examples more realistic examples and we'll take it from there if you remember from the promise episode there are two parts to any promise the promise Creator and the promise receiver in other words there is a part of your code that creates a promise and returns it like this function and then there is another part of your code that receives that promise and does something to it using the den and catch block we can actually get rid of the promise variable here and write it like this a little simpler so take a look at this result variable right it's inside a then block that kind of annoys me right I don't like the fact that it's in inside a separate block but we need to do that because this is a sync code right but wouldn't it be cool if we could write async code as if it was synchronous like regular serial code reading from top to bottom one line at a time instead of nesting code inside then code blocks something like this where we just create the result variable and assign it to the return value of this get data function well no because get data doesn't return the actual value right it Returns the promise of that value that will resolve sometime in the future I explained in full detail over here in episode 11 or in this one minute YouTube short about promises the bottom line is Javascript thinks this is synchronous code and doesn't wait around for the functions async operation unless unless we put a weight in front of the function invocation hold on ah espresso are you serious I mean we can just do this by putting a weight in front of the function well let's find out Craig to the browser alrighty so let's create a promise let's actually first create our function get data and what does it do it returns a new new promise and the promise resolve this should be familiar to you already if you've watched episode 11 12 actually one of those so we knew we get a resolve and a reject we're just going to do the resolve real quick uh I'm gonna fake a little timeout action one millisecond because I want to be back to the browser then I'll do a resolve and I say number 46 because why not 46 and 2. it's the enemy okay then what do I want to do okay so now let's just call our function and see what happens because the result equals get data then what do I want to do I want to console log my result result and I just found out that I have a typo set timeout and we do that and boom okay so it's obviously just a promise now what if I put a weight like I was saying it's gonna work I put a weight in front of it and boom syntax error awaits is only valid in async boom uh in async functions and the top level bodies of modules okay so what does that mean so what's happening here the reason why it's called async await is because in order to use a weight you need to use async in other words I'll wait right here is only usable inside functions that are async and since we're not inside a function let alone an async function we can't really use it that doesn't like it it's going to yell at us so let's put it in a function first a function I'm going to call this start uh not a great name but it will do for now and so now we're inside a function uh but it still says it doesn't like it because the function has to be async so how do I make an async function I just put async in front of the function that was easy now what do I have to do to make this work I just have to call my function start and the result shows up 46. so that is pretty freaking cool right so here's the magic I can call get data as if it was just a synchronous function right and I can assign its value to resolve whatever it returns to result but not the promise right it does return a promise but it actually waits for the promise to resolve or reject we'll take a look at that in a second assigns the value to result and I can console log 46. by the way icons will log just to show you that now I have access to the real value that I eventually wanted to get the the resolve the fulfilled value of that promise but obviously you you want to do more than just results right you can do whatever you want to do here so usually I just use console log just to show you that you you now have access to 46. so this is the difference between this and uh let me do I'm gonna do one more function um just to put them side by side so you can see as a reminder uh we don't want to assign it we can say that then again uh data or result I guess I'm trying to be generous here to our then block and this this syntax that we looked at before so I can say console.log results at this point I will receive it and I'll be fine right so I think this is fine I don't think I left anything out here so it's the difference between this and this so which one do you like more I mean I for one much much rather write it like a synchronous kind of top to bottom kind of way instead of creating these catch blocks and then blocks and oh yeah so if I want to catch the error I'm gonna have to do the catch and so on and so forth right we've done that in episode 12. so I'm gonna get rid of this and again the point is that I can start using the result of my async operation as a regular variable as opposed to some internal variable that's declared inside a den block so let's simplify a little bit actually because we're right now we're faking it right we're faking uh an async operation so I what if I I don't want to use timeout anymore so what do we do instead we can use let me get rid of this get data because it's kind of like a middleman function that I wrote let's use fetch fetch is a a native browser feature and you can just use fetch to call back-end endpoints and receive data so I'm gonna I'm just gonna use that instead of using this fake set timeout that I had by the way fetch is the topic of episode 14. so next episode so make sure you check that out foreign Focus so we know fetch returns a promise so I can treat it the same way as I did with my get data function I'm actually going to copy this URL from where you can't see because I don't wanna I don't have to type it so let me zoom out a little bit uh well maybe I can do this I want to try and get everybody in this on the same line okay so hopefully you can still see that so I'm going to wait for the results of the fetch the fetch call and then uh something funny about fetch is the result is actually it needs to be jsonified so let's just say data that comes back and then the actual result which we were looking for before it has to do another await on data.json I'll explain all this next week maybe whenever I do the next episode and then I do console.log result let's see where we end up uh whoa that's a lot of stuff I don't need okay so I need result dot what does this object look like uh has properties I think properties uh yep it has that and then I whoa it gives me so much stuff so this this is actually the specifics of this particular API I'm using the weather API from the government and it gives you way way too much uh and I don't need what do I have one so I'm just getting the latest uh short forecast yep let's do that boom and that so okay uh very nice I actually am able to get some data from a real API get my data and write it in a way that reads top to bottom there's no additional code block or any event or catch that I need to create so the result variable is now pretty much accessible for me to use and I can do whatever I want to do with it so that's the magic and so let's compare it now to I'll write this uh one more time as a start two like I did before as if this was written in the old format that then I can get what do we call that data so data comes back and then what do I want to do I want to do date data Dot Json yep and then there will be another then which will give me result I could be naming these a little bit better but I'm not so if I do this right so let's do that if I do start two do I have any bugs nope it's fine it does the exact same thing so it's the difference between these two uh between this mess which oh look at all this indentation and all this weirdness uh versus pretty straightforward lines top to bottom right very nice so a few important points about uh async away async await has to be done both of those keywords have to be used together like you saw in in the beginning it was yelling at me when I was using a weight without using async uh you just you're just going to get a syntax error except for two pretty common scenarios so those two are a a weight can be used without async with JavaScript modules now I don't want to encourage or discourage it that's kind of up to you I'm going to put a link below to mdn you can read more about it on mdn and decide whether you want to use it or use that or not and the second thing is Chrome devtools actually allows you to write await and use a weight without the usage of async as of chrome 62 so it's been a while Chrome is up to I don't know when I'm shooting this it's it's around 106 or 107 108 so it's been a while so Chrome Dev tools which is something I use a lot which you probably have seen if you've seen the previous episodes I use it a lot for debugging and for testing things out and just around with JavaScript Chrome Dev tools assume that you're in a I believe they just create some kind of a JavaScript modules where you can use a weight without using async so just keep that in mind if in case you don't see the syntax error and you think wait a minute it was Cena boating me about those two keywords having to be used together no that's why so devtools gives you that that kind of luxury number two async await only affects the promise receiver not the Creator the Creator implementation stays the same so when using async await you don't change the promise creation side you can leave that alone you only change how you handle the promise right so it's just a nicer syntax to write versus the the then block three you can put a weight in front of any function that returns a promise like you saw we did that with get data which was a custom function that I wrote that returned the promise and we also saw it done with fetch which is something that's um just native to the browser for any function almost can become async so can I put a sink in front of let's say object methods sure you can really here's an object called me and it has a method called say hello that returns a string it doesn't even return a a promise and as soon as I put async in front of the function or method boom now it's async this means I can perform any async operation inside the function and await the result I don't have to do anything async in there but if I did I could write it with a weight and it would be pretty pretty easy something like this and also you might have noticed the next point point number five acing functions return a promise by default right so if you convert a function to be async it will make your function return a promise by default even if you explicitly return something else like a primitive like a string or something it doesn't care check out the oily example it looks like it just returns a string right but it doesn't it returns a promise a resolve promise right the promise isn't pending but it is a promise that's resolved number six one of my uh favorite things or one of the most neglected important and neglected JavaScript skills which I should probably dedicate a whole episode to is error handling so in episode 12 with promises I showed you how to handle errors using the catch block we spent almost half of that episode talking about error handling when we start using async awaits and we don't have the them block then we probably don't have the catch block either right well kind of you can use a catch block with a weight but also you can catch the error using a much more old school method called try catch let me show you how it works so back to the browser let me just copy this from here because we already wrote it and so instead of resolve right this is what we had before I am going to reject and say something went wrong and so now I'm going to async right async function just like before star T start and I'm going to invoke it uh and what am I going to do so I'm going to do the exact same thing let's actually just write it first and then we can add the try catch result await uh get data so it says uh something went wrong on on un uncut in promise if I now uh put a try catch in here and actually move my thing here uh catch it's going to accept an error and console.log uh let's do one of these error and I can do that error and it says so now now we're catching our error inside the catch block and says uh error something went wrong so this error comes from this reject so it's the kind of similar to The Catch block of promises that we looked at in episode 12 but it's it's slightly different in the way we write it now with that said you can still I'm going to do a start two one more time and compare them side by side start two start two if I do a regular function and this and do this boom I can do a DOT catch and say error whoopsy Daisy so this is my catch block so you you could mix and match them if you really wanted to but there's a couple of problems here like if I actually if I do a catch so here's where it gets kind of messy let me um let me comment that out for a second so let's say this is the happy happy scenario right I have that okay and resolve let's say we resolve it right and it's not something went wrong reject but I won't call the reject and say here's your data here is your data and we're going to resolve so great this is in a normal situation with the with a success scenario this is fine this code works but as soon as I add the catch block to it um but I still want to log my result because I still want to yeah I want to use use the result variable the the value that comes back from this the problem is if it rejects it it does go into the catch block but it's still the uh the rest of my code is still going to run so that produces a few really big issues for me for one thing this is bad because we don't want any of our success logic which is here this console log again this is just a replacement for what we would normally do if it was successful say I want to add it to the Dom or I want to pass it to another function to do some kind of calculation or whatever else I want to do with it this code will still run even if I have a catch block so this could potentially create a bunch of different bugs for me I don't want this code to run if there is a catch right so if the promise was rejected My Success code is still going to run that's not good but also we need to separate out our success logic from our failure Logic for a bunch of different reasons for readability for testability for organization if I if I do this they're they're kind of entangled with each other they're too close to one another versus if I get rid of that and start let's do our start usual um my console.log success whoops success I'm gonna try to type it the same way that as my failure so they're kind of similar what I can do is I can totally separate out these things and I can say I can create separate functions for organization on success I can say you know do that on success and on failure I can I can create another function called on failure right and so what's what's cool about this is that now my success Handler and my failure handlers are totally separate right and lastly what's the point of writing async awaits if you're not going to take advantage of the async of the synchronous looking nature of it so that's why in the industry most people as a standard use try catch when they use async awaits I'm going to get rid of all this clutter here just to show you a little bit more cleanly where we ended up this is going to be my failure and this is going to be my success and this is pretty nice right now are you going to be able to find some tool who would find a case against what I just said and find a scenario where mix and matching would work sure but I don't recommend it I don't like it to wrap up my thoughts about async away and why we should use it I think hopefully it's clear that we use it mostly to make our code more readable it doesn't really add any sort of functionality or feature that promise handlers with the then and the catch block don't give us already but it's just a much nicer more synchronous looking way of writing promise handlers okay so before I wrap up a few things but first some water stay hydrated kids so number one we reached 20 000 subscribers right before I shot this episode so this is a huge milestone for me 20 000 on the way to a hundred thousand the more you have the more you want right so but I wanted to say thank you all for subscribing I don't like to beg for likes and Subs like some others do so to see all you guys and gals out there show interest in my work is really rewarding so thank you very much second thing is I'm going to start a color code podcast I'll be talking about similar type of things that I talk about here on YouTube and do some audio tutorials and see how that works I don't know too many people who are doing that so I'm interested in seeing how that works and interviews with with friends and other engineers and other tech people and just like my old drunk web podcast if any of you been following me since the good old days I'm looking for a name for this podcast if you have any suggestions let me know in the comments below and if I choose the name that you suggest and if I hadn't thought about it myself already I will send you some color code merchandise and speaking of color code has an Etsy store now so you can buy T-shirts and mugs the mugs are really cool it changes color when you add hot water to it so it can tell you if your tea or coffee is still hot so yeah check it out next thing is I'm redoing the color code website so if you see something not working there it's because it'll be replaced soon with a new version I plan on making a video episode for YouTube and talking about how I rebuilt it in just a few days refusing react 18 next js13 the the one that just came out for sale Firebase graphql typescript all that good stuff stay tuned for that next thing is I've started to post YouTube shorts the one minute versions of these videos that I'm teaching so check it out and let me know if you've seen those and what you think of that format last but not least my JavaScript Mastery course many of you have messaged me and continue to message me on Instagram and asking me about what even on LinkedIn uh about you know what's going on with that and when it will be available I know it's taking a while it's taking longer than what I expected but I have an extremely demanding full-time job Outside YouTube and I'd rather wait a little bit longer and put out the best course that I can put out for you versus rush it and put something mediocre and average out there that you can already buy on udemy for five bucks so more on that later I promise I'm working really hard on that and that's it I gotta bounce thank you for watching this was episode 13 of the 20 part series called 20 things JavaScript developers should know but probably don't see you soon [Music] [Applause] [Music]
Info
Channel: ColorCode
Views: 67,597
Rating: undefined out of 5
Keywords: ColorCode, JavaScript, JS, ReactJS, es6, inheritance vs composition, javascript for beginners, coding for beginners, jS inheritance, js tutorial for web development, Prototypal inheritance javascript, Javascript prototype, javascript objects, Web development 2021, web dev, Async, Asynchronous, Async await, Promises, callback function javascript, async await javascript, asynchronous javascript, callbacks javascript, callback event, js modules, async await javascript explained, callback
Id: spvYqO_Kp9Q
Channel Id: undefined
Length: 24min 29sec (1469 seconds)
Published: Tue Jan 03 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.