Asynchronous Javascript Tutorial - Promises and Async Await Explained

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
guys how's it going i'm back here with another video and today in this video i'm going to go over um everything related to asynchronous programming in javascript so i will start by talking about promises and then i will transition into talking about the async await keywords that you can use in javascript and i will explain everything as i would like to have been explained to me when i was a beginner so before we get into the video this video is sponsored by letter which is an amazing company which i will talk a little bit about it right now as many of you guys know i am currently a undergrad student at a university and i honestly find it really hard to find a job or just career advices on websites like linkedin and for that reason i am excited to tell you guys about letter which is a platform that is designed for students just like me honestly it is an amazing platform where you can just share uh your struggles or your success stories and if you want to you can also just post anonymously there's also a job board which is really awesome because people can just share different job opportunities that they found so that other people can apply as well or maybe uh you can just use the platform to promote yourself to recruiters by putting your resume put information about you and just talking to different people from the industry and ladder is an application based platform so it is very simple and easy you can just go to the platform apply for it and i'll be posting there as well there are several communities that you can engage with and if you want to check it out i'll have a link for the website in the description okay everyone so let's start with the tutorial you can see that i just have a very simple application over here it is an ogs application but javascript runs equally everywhere so i'm just going to run this in my terminal and you can see that when i run an application like this it should actually just console log so if i do something like node index.js it console logs hey right and it would happen the same the exact same thing if i did it on the browser as well now why did i bring this up well the first thing i want to talk about is the fact that normal javascript without using promises or async away just javascript that you write in general runs almost like instantly right so if i console.log this over here and i actually have a variable over here let's create a variable called um name and set it equal to something like pedro right and i want a console.log pager over here or our name over here you should see that it should console.log pedro because it is almost like instantly right we are creating a variable it recognizes it and it console logs the value of it and if i change the name to be equal to something like john and i console log it again by saying console.log and i console log name again you should see that it will change the value and the console.log log will satisfy the new value because changing uh the value for a variable is instant in algorithmic like if you think about it in computing time and thinking about how long it takes for an action like changing the value of a variable in your computer system it is instant so that's the reason why when we console log the new value it actually console logs the new value and it doesn't take any time to change the value of name now this isn't the case for every application the reason for that is because if you've ever worked with a front-end application where you need to i don't know fetch some data from an api you might know that not all api requests take the exact same amount of time and that makes sense it depends on many factors it depends on your internet speed it depends on just how far away are you from the server it depends on how big the request is it depends on a lot of stuff so for that reason if i were to do something like um i don't know let's imagine we have an api and i want to fetch uh data related to a list of movies and i created something like list of movies and i just said this to be equal to fetch and i fetched some data imagine that this is a url uh it's obviously not a url but imagine it is um and i'm fetching data from this api over here now if i came over here and said console.log list of movies this would probably not work and the reason for that is because when you fetch this data right it's going to take a little bit more time it's going to take maybe 500 milliseconds maybe one second maybe something but it's not instant we know that because you're fetching data from a server and that takes time and for that reason when you console log this over here the data that is over here isn't going to be the data that it actually fetched from the api because what javascript will see over here is it will see that you're fetching some data and setting it equal to a variable but it's not actually like telling the the program to wait for this request to be done to then continue moving forward with uh whatever you wrote over here and console.log the list of movies so for that reason um many languages uh deal with this in different ways um the the first proposed idea to fix this in javascript i believe was using promises okay guys so as you can see over here i just wrote this example over here and i'll go over exactly what it means but basically a promise it's almost like an object in javascript it is something that is pre-built in javascript and it deals with stuff like waiting for data to be done but on its core you don't really need to do it that way so a promise as it is in javascript it's just a class that you can invoke as you can see over here i created a variable called event and this will be our promise and when you set it equal to a new promise basically it will take in a function which can have two arguments to it the first argument is a resolve and the second argument is reject then instead of this function you can write some sort of logic that will define this promise and by the way if you're starting to get a little bit confused don't worry i'm just showing you the core like idea of a promise initially but then it will become a lot clearer as we go on with examples of how we actually use promise because most of the time we won't be creating our own promises we'll just be using promises that are returned and we're going to deal with them so what exactly does this do well resolve and reject are two things that we really need to take into account resolve is just a function that we called when we want success to happen right when we want something we want to say like okay if some condition is true we want to uh resolve this for this promise and we want to re return some sort of value or we want to um deal with some sort of success part of our function right and reject by the name you know what it means it's probably it is failure right when you want the function the promise to fail when you want some sort of error to occur you call the reject function so in the example that i created over here it is pretty dumb but it's pretty simple i created a variable called name and i set it equal to pedro and i just asked if name is equal to pedro then result call the result function and if it is not call the reject function now how do we know what is the resolve function and what is the reject function it's this is kind of how we're dealing with errors right if name is equal to pedro do something related to this promise being a success and if it's not do something related to it being an error so error handle inside of this reject function but how do we determine what the resolve and what the reject functions are well we just come over here we grab our promise which in our case is called event and every promise that exists in javascript contains something called an a dot then and a dot catch like this now what exactly are the dots then and the dot catch well the dot then is a function that will be called if we resolved and a dot catch will be called if we're rejected now think about it this way um over here if i want to say like okay name is equal to pedro what do i want to do if this is true well i can create a function inside of this dot then and i can just console.log the name right technically i can just come here and say pedro but one thing you can do is you can pass arguments to this so for example in the result function i want to pass the name which will be pedro and i can grab that inside of here and i can just console.log name now if there is any errors i want to catch it it's almost like a try catch so right now i'll just say error over here and we can control log the error we're not passing any error inside of this reject because we didn't over here but what i can do is i can pass a message saying something like uh name was not pedro name was and then i just passed the name over here which right now this won't happen because name is equal to pager now what exactly should happen if we run this application well let's see it if i open up my console over here and i clear everything out and i just run node index.js you should see that a console logged pedro despite us not having any console logs like outside of this promise it recognizes that the name is equal to pedro it resolves the function passes the name into it and when we define what the like the success and the error functions of this promise will be we say that we want to console.log it but if i came over here and i said that the name is uh i don't know john you should see that if i try to run this again it should actually say name was not pedro name was john and this is the kind of this is kind of the idea of promises but one important thing to understand is that the main aspect of promises that you will be working with is this over here because what happens when you make an api request is you can say like okay if the api request is done if the data has been received then we want to do something and if there was any errors in the request then we want to catch that errors over here that specific area over here so this is what we'll be using most of our time and there's also something else which is the finale case which you can also just put it over here like this finally is just uh something that will be called no matter if it was an error or if it was a success so i'll just say promise uh finished or something like this and when i run this again it doesn't matter if if name is equal to pager or not it will say promise finished if i change this back to pedro you should see that the finally case will again be console logged and will be called now how do we apply this to actually fetching data how do we make it so that this will work with fetching data well i'm going to come up with an example over here actually use an api and i'll be back in a second okay everyone so as you can see i came up with a very simple example over here using an actual api that exists and if you want here's the link for the api all it does is it returns a list of facts about cats so it's a very simple example but i wanted to use this in order to show you guys how promises work when working with um fetching data now you can fetch data in many ways and i do have videos where i teach you guys the different ways of how to fetch data from an api the way i'm going to be using uh in this video is by using a library called axios so if you want to install it you just come over here and say npm install axios or something like this or it just depends on what like where you're doing this where you're using this but axis is a very famous library which allows you to like fetch data from an api so you can see over here i said exuse.get and i put the url for the api the reason why i did this is because i want to get the data that is returned from this api however how do we do this in a way such that um we we tell our javascript code to wait till the data has been received from the api request to then do something so i technically want to um just for example uh console.log the data right now if i do something like this i say cons data equals to axis.get if you are not familiar with the idea of of promises and async or weight you might think that if i console.log over here data it should work but look what happens when i do this when i come over here and run my application you should see that it returned a promise and it says that the status is pending the reason for that is because what what this returns over here and any other method of fetching data it will always return the same thing which is a promise and as we talked previously a promise isn't a value a promise is almost like an object a class where you can find different aspects of that val of the class by either trying to see what happens when this succeeds and trying to see what happens when it fails so what i mean by that is basically if i really want to get this data i need to resolve the promise by saying something like data dots then so like after this data has been received we want to run this function over here and this will only occur when the data finally comes from the api now if we want to catch any errors i can also just say data i just can just put like dot catch over here and catch any errors that occur now most of the libraries they already have built in they already like in the promise that they are returning they already include um arguments to the dot then into the to the dot catch so whenever you fetch data the data will be responded over here and you can just grab the data by grabbing the argument of the function when the promise resolves when the promise succeeds and the same thing goes for the error i can catch any error and grab the error by using this over here now what i can do is i can console.log over here saying um just the data i just want to console out the data if we receive it and if there's any errors i want to console log the error like this now if i remove this you should see that now if i run this application by just coming over here and running it what should happen is we should get a list of data and you see that it kind of took like a little bit right to to run it actually we didn't get a list of the data because we're console logging this over here which is uh oh i can select the data instead i want to console the res so let me just do this again you should see that we actually get a bunch of information related to the request if we want to access the data that was returned from the api i can say something like res.data and you can see that we actually get the data that was responded right that you can see we get a bunch of facts about cats but the important thing is that we're actually being able to fetch data from an api and see it in our application now what if there's an error right for example imagine i forget to put the s over here it will definitely cause an error because this over here shouldn't be actually i'll just write random words this api doesn't have this endpoint so what happens in this case well let's run it again and you can see that this was caught right um it said um it gave us an error it's just saying that this it wasn't able to get the data that we were requesting so it means that the promise is successfully like dealing with everything and if i also want to put a final case over here i can say finally and i can say something like um promise like console.log promise resolved right and this should work perfectly now what is the point of this right the point is that we were able to tell our application to wait for something to happen to then continue moving forward we're waiting for the data to be returned so that we can continue doing and like doing something with the data maybe manipulating it maybe displaying it in our screen whatever we want and promises is a great way to do this now there's a different way to do this which was introduced a little bit later in the javascript journey or timeline which is using async await and i i don't want to debate on which one is better they're different in many ways i do think that async await makes code look cleaner and i think many people would agree with that um but basically async await is just synthetic sugar in the sense that it is doing the same thing but it's decreasing the amount that you need to write to makes the exact same thing happen and the way you use async away to do something like this it's pretty simple well the first thing you need is you need a function you need to make a function because async await only works when you create a function that is declared as asynchronous so for example if i create a function over here called get or fetch data like this and this function all it does is it just makes the api request and it returns back the data right or console logs the data well what i do is over i put this logic inside of here and instead of saying then dot catch all the other stuff that i mentioned before we just make this function async by putting async keyword over here right before the parentheses and if you're using um like normal javascript without the the arrow function syntax you can just say function the name of the function like fetch data like this and you put the async right over here so you say async right over here and this function should now be an asynchronous function well both of them do the exact same thing but the important thing is that we have this fetch data function that is now asynchronous now the first thing i want to do is i want to first of all fix this url over here because it is clearly not working because we changed it so the correct api endpoint is slash facts and i just realized i also accidentally put an ass over here so let's we can just remove it and this is the correct end point to make our request now if i came over here and i said console.log data what do you think would happen well we made this function asynchronous and we're making the api request but what exactly will this console log because we're just we're just made the function asynchronous and we don't have a dot then we don't have a dot catch like how would this work well let's try it if i came over here and i call the fetch data uh function and we ran this again you see that it console logs something but it console logs a promise that is pending meaning that we didn't resolve the the actual promise we didn't we need a dot then or a dot catch to resolve the the promise but that's counterintuitive because i just told you that async await is a replacement for uh promises we are using the dot then dot catch um syntax well that's true one thing that we need to do to make it so that it will work is the fact that every function which is asynchronous will will do nothing if there isn't something inside of the function telling it to wait so the await over here just means that whenever you have something in your function which returns a promise you should put the await after the equal sign so like i said that i want to declare the variable data to be equal to await whatever promise this returns and now this over here will wait for the promise to be resolved and then console.log the data so if i actually come over here and i console log this again you should see that it is actually console logging whatever was returned in a dot then which means it is doing the exact same thing but without the the whole like synth the whole like a bunch of code writing.then dot catch and dot finally so you might be wondering now okay this this fixes the issue where we can in one single line of code we now can say dot then and get the actual results but how do we error handle in this case because in using promises uh we just say don't catch and it it easily catches the the errors and nothing happens well to error handle when you're using async await you need to use the classic try catch method so we'll try to do this over here um if it succeeds then it succeeds perfect but if it fails and there was any errors in the network request then we can catch an error and the error will be passed over here as an argument so i can just console.log this error and you'll see that if i come over here and i again screw up the the ul and i run this again um it should now console log an error and not the actual like request because like it was an error so it doesn't it doesn't it didn't pass through this it tried this it failed and then it catched the error now the last thing you guys might be wondering is how do we um use the finally like dot finally uh property that we had with um normal promises or with the notation that i showed you guys in the beginning well this is interesting in javascript you can also just come over here and write finally and put a case for finally and you can just console.log something like hello now you might argue that this over here is the same size as the dot then dot catch and uh like what i showed previously well sometimes it is but sometimes it isn't both do the exact same thing so i wouldn't be too caught up about like which one to choose depends on each situation for example um if you like technically i would say that async await looks better but um it just looks better you know what i mean right i don't like having callback functions i don't like having to say then dot catch and i just prefer this syntax but you can choose whichever one you you want and use it in your project and now you you probably know um how asynchronous programming works in javascript now this is a concept that is very useful and very important throughout many languages so i really hope you guys gained value from this video and if you like the video leave a like down below comment what you want to see next subscribe because i'm posting um two to three times a week and i would massively appreciate if you guys could support the channel don't forget to check out the sponsor of the video the link will be in the description thank you ladder for sponsoring this video and i'm really thankful for everyone who watched the video as well so that's basically it leave a like subscribe and i see you guys next time [Music] [Applause] [Music]
Info
Channel: PedroTech
Views: 1,832
Rating: 5 out of 5
Keywords: computer science, crud, css, databases, javascript, learn reactjs, mysql, nodejs, programming, react tutorial, reactjs, reactjs beginner, reactjs tutorial, typescript, react js crash course, react js, node js, express js, pedrotech, traversy media, traversymedia, clever programmer, tech with tim, freecodecamp, deved, pedro tech, async await, promises javascript, javascript async await, javascript async, javascript asynchronous explained, javascript promises
Id: PgZ9npYJZzU
Channel Id: undefined
Length: 23min 3sec (1383 seconds)
Published: Wed Sep 15 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.