Async JS Crash Course - Callbacks, Promises, Async Await

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hey what's going on guys so this is gonna be a crash course in asynchronous JavaScript so we're basically going to cover a couple different things I want to cover callbacks promises and also the asynch of weight syntax now these are all ways to deal with asynchronous data and what that means basically synchronous is when something's going on but you don't want to wait until that thing is done to continue your program you want to continue while it's happening so what's happening asynchronously rather than synchronous programming where something happens and you wait until it's completely finished until you move on to the next now asynchronous programming is is very relevant to JavaScript because we're often making requests to servers elsewhere and it can take a couple seconds to get your data back for instance and you might not want your program to stall and wait for that data to come back you want to keep going and and keep doing something so this is where callbacks come in and callbacks were used for a long time until es6 was released or es2015 where promises were introduced to the language and promises give you a more elegant way to handle asynchronous data and then in I think it was es7 async await was introduced which is still dealing with promises just in a different way you're dealing with the response in a way that's a little more elegant and it looks it looks more like synchronous programming rather than using the dot then and so on if you guys have ever used promises so we're going to cover all those things initially I wanted to do I was going to do a separate video on them all but I figured they're all relevant we're actually going to use some of the same code and the callbacks and promises you can see what you have to do to basically change it from a callback to a promise we're also going to take a look at promise dot all where if you are resolving multiple promises you can do that you know call them all at the same time and wait for each one to beat and a lot of this code is actually from my modern JavaScript from the beginning course on udemy so if you're interested in 21 and a half our course on just vanilla JavaScript just core concepts building some projects check that course I'll put a link in the description alright so let's get started here I just have an index.html file I have a callback CAS and it promises dot J s and we're gonna start with callbacks and you can see I just have look this should actually be callbacks down here alright so let's go over to callbacks j s and what we're gonna do is we're gonna kind of mimic Pope blogposts on a server and getting them and then creating a blog post so we're just gonna have an array and call it posts and we'll have an array of two posts these are just gonna be objects so title post one and body I'll say this is post one and let's copy this down and then we'll have one more post so this will be post two and I realize that a lot of you guys might already know this stuff but you know I like to create you know beginner to intermediate videos on my channel so people just learning this stuff you know it's R it's really important and I mean there's not in my opinion there's not a lot of great resources out there to learn this type of stuff at least videos you know there's a lot of documentation but a lot of people don't like reading documentation so what we want to do here is create a function called get posts okay now remember we're mimicking how how it is to fetch from a server and that could take a couple seconds or whatever so we're gonna use set timeout here okay set timeout is just it takes in a callback function so we could put a function in here and then it takes in a certain amount of time where you want to delay whatever you put in here so I'm going to delay it by a sec so we want 1,000 which is 1,000 milliseconds now you can use this syntax or you can use an arrow function which is what I'm gonna do so I'm going to remove the word function and just put in an arrow like that okay we'll keep this es6 style so inside this set timeout I'm going to the purpose of this is to get these posts here and then put them on the page so let's do let's create a variable called output we're just going to initialize it to nothing and then we want to loop through the posts so you could use like a for loop here if you want but I'm going to use the high order for each method so I'm going to say posts posts dot for each and then this actually takes in a callback as well you could put function in here but I'm just gonna use an arrow function and then as far as a parameter goes I'm gonna say post this could be anything but I'm gonna call it post because that's what it is he can also use passing an index if you want and then for each post we want to add it to the output variables so let's say output and we want to append so I'm gonna say plus equals we'll use some backticks here so that we can use template syntax our template literal whatever it is and then we're going to just put in a lies here and I want the post title so I'm going to use this syntax so I can you put a variable in we'll take that post which comes from this right here so basically we're iterating through here and then we can grab the title or the body so I'm just gonna grab the title so post title and then right after the for each not within it but right after it sorry about that guys sorry about that so right after the for each we want to just insert it into the body so I'm going to say document body dot in our HTML does really matter how we how we insert it here and we're gonna set that equal to the output okay so we need to actually call this function for it to work so we'll say get posts and let's save and then what happens is after a second remember it's in a set timeout for a second it's gonna load the two posts okay it did great we get it here the posts from the array and then we're looping through and then we're outputting them or we're putting them into the output variable and then outputting that on to the page with this line alright so pretty easy now let's create another function called create post okay and this is going to take in a new post that we pass in and we want to do a set timeout here as well because remember we're we're hypothetically dealing with a server so let's say set timeout we'll put an arrow function here and let's say this one takes two seconds so 2,000 milliseconds and inside here all I want to do is take posts and I want to push on to the post array the new post like that so what what do we want to happen we want to get the post and then we want to create a new one that's it right so let's do it let's say create post and let's pass in an object here with a title and we'll just call it post three and the body will say this is post three okay simple we get the post then we create the post save wait a minute unexpected token one oh I forgot the function all right so there we go post one post two where is post three now the reason that we're not seeing post three is because the create post took longer than the get post the get post happened in one second okay our server returned it in one second the create post however took two seconds but by the time we ran this create post this it was the dom was already painted okay so we can't do anything beyond that point so this is where asynchronous programming comes in and this is where callbacks come in which is one way to handle it so let's do that let's let's actually make this work by using a callback so this create post here what we would do is we would actually have this take in a function and we'll use we'll call it callback because you could essentially call this anything but this is common practice and then we want that function to be called right after that post is pushed on okay so right here will say callback like that and then all we have to do is now make this get post this callback so that it runs right after this is pushed not waiting two seconds for the entire function so we can completely get rid of that and then add in the next second parameter of get post like that okay no parenthesis and let's save and see what happens okay so what happened is it waited two seconds and then it showed all of the posts and the reason it waited is because it had to wait to create the post before it actually called the callback okay so it had to push on to it and then call a callback and this whole thing took two seconds but it adds the extra post okay so this is a good example of how callbacks work and why you would use a callback so let's now look at promises okay and I'm gonna basically use the same code or start with the same code so we don't need the actual call here so let's grab the posts and the two functions and let's put them into promises all right and let's change in index.html we'll change this to promises dot J s okay now the get posts we're just going to leave okay we can leave that but for create posts what we want to do is instead of passing in a callback we don't want to do that and we don't want to run the callback instead we want to return a promise so to do that we want to simply return a new promise and then a promise takes in a callback I'm going to use an arrow function and it takes in two parameters okay so it takes in resolve and reject so basically when you want to resolve a promise successfully you call resolve when something goes wrong if you have some kind of error you want to call reject so we want to do the same functionality here that we did we just want to put this inside the new promise like that and to resolve actually what I'm going to do is just create a variable called error and I'm gonna set it to false normally this would you do some kind of error checking you don't have to but if you wanted to you would do some kind of error checking and let's see if that is not true so if no error then we simply want to resolve when I resolve our promise else then we want to reject and we want to send a message we'll just say error something went wrong okay and that's it so let's go down here and let's call create post let's pass in our put our actual post so we'll say title post three and body will say this whoops this is post three can't type okay now we're not going to pass in a callback like get post so we're not doing that anymore we're this returns a promise meaning that we can now use the dot then syntax so we can say dot then and then in here we want to pass in get posts like that all right so let's try and run it so we'll save and there we go so basically it's waiting it's gonna it's setting the timeout and then as soon as it's done it's gonna resolve once it resolves then it'll call get posts okay now if we wanted an error message like let's set error to true so since air is set to true it's going to reject now if I save this and run it we get an uncaught promise okay or an uncaught error so the solution for this and you guys probably use this before is dot catch so under the dot then we want to do dot catch and pass in error and then let's just console dot log the error and save and now you see that we get whoops I spelt that wrong something went wrong yeah I can't spell that's a winner wrong but now you can see that we're actually getting a nice clean error rather than just an uncaught promise or whatever in in for the most part in my experience you're mostly going to be dealing with promises so for instance when you use the fetch API or Axios or anything that uses promises the Mongoose library for DB for nodejs uses promises you know more and more libraries are using promises now so you're mostly going to be dealing with the response rather than creating them yourselves but you should also know how to create them yourself which is just basically new promise so what I want to do now is look at promise dot all because if you have a lot of different promises you don't want it you don't want to keep having dot then dot then dot then so you can use to promise dot all in that case so I'm gonna comment out this call and let's go down here let's actually change the error back to false to and let's look at promise okay so let's just create a bunch of promises will say cons promise 1 equals new actually we can just simply do promise dot resolve okay as long as we resolve it and we'll just say hello world and then we could say promise to we could just set this to a variable like 10 if we wanted to and then just give me different examples we could say new whoops promise 3 equals new promise and we could pass in function with resolve reject and let's set that to let's do a set timeout and we'll call resolve and let's call that in two thousand milliseconds and we'll just pass in goodbye okay so now what we can do is we can call promise dot all and what this does is it takes in an array of promises so we have three of these up here let's say Promised One let's do promise to and promise three and then this will take a dot then so we want to do a dot then and pass in here or a callback so we'll use an arrow function and it will take in values like that and then let's just console.log so we don't need that let's console dot log values all right let's see what happens if I save this alright so what happened is it gave us back an array with the hello world so the first promise the second which is just a number and then this one goodbye which we actually set a timeout of two thousand or two seconds and that's why it took two seconds to actually return everything it's gonna take however long the longest promise is that's how long it's going to take to actually do to actually show us the values all right and just to add one more thing in here let's say Const promise for now well I'm sure a lot of you guys have worked with the fetch API to make Ajax calls or to make HTTP requests I should say which returns a promise so let's fetch from let's see let's use the Jason type a code or jate what is it it's Jason placeholder dot type echo calm and we can make a request to let's say the users right here and get users I'm gonna grab that URL and pass it in here now this returns a promise now fetch is a little weird because what happens is it is you need to do two dot bends when you use fetch because you first need to format it usually to Jason and then the next dot then will actually give you the data so if I keep it as is and I pass in promise for and save it's gonna work but let's if we look at the response here we just get like this weird stuff what we want to do is for fetch we want to do dot then and we want to map the response to res dot Jason like that and now if we run it it should give us the actual data which you can see right here is gonna be ten users all right so that's promise not all pretty easy now let's look at let's see let's look at a sink await okay so I'm going to comment this out and we don't want to change any of this stuff I mean a sink await it's a way to handle responses it's not like a different way to write them or anything basically we need to have a function that's labeled asynchronous so let's go down here actually we'll go above this because this promise dot all has nothing to do with the code above it let's say a sink oh wait alright so what we want to do is create a function and I'm just going to call it an it now this function has to be labeled async if we want to use a weight inside of it and a weight does just that it waits for an a synchronous process or action to complete so what we'll do is we'll call create posts okay so I'm just going to copy this here without the dot then just simply the create posts with the the title and the body passed in except we want to call right before it a weight okay and then after that we can just simply call get posts so we're waiting for this to be done until we move on and call this so now we just need to call an it and let's save and we should see them pop up on the screen and there we go alright so that's how a sync away it works it's just a more elegant way to to handle promises now if we wanted to use it like let's say with fetch we could do that as well so I'll go ahead and comment that out let's go out here let's say a sync oh wait with fetch okay so let's copy what we did here just grab that and we're gonna need an async function let's just call this we'll say function fetch data or fetch users and then we want to call that fetch except we want to put this into a variable and let's call it response or res and set it to a wait fetch because remember this returns a promise now again the fetch API is a little weird because the first promise it returns is gonna its we're gonna need to call res dot Jason on that so what we would do is create another variable called data and set it to a weight and then res dot jason like that and then we could console dot log the data so let's save that and it's not gonna do anything because we didn't call it so let's call fetch users and save and there we go so we should get 10 users ok so it's just a cleaner way of dealing with promises instead of doing the dot then and all that stuff especially with fetch makes it look even nicer we just have these variables and everything is just one after another there's no dot then or dot you know whatever and it's it's cleaner than callbacks as well so I mean that's pretty much it guys I wanted to just cover the basics and kind of you know for those of you that that weren't really wrapping your head around this stuff and I know a lot of you already know this and that's fine you know a refresher never hurts but that's gonna be it guys so I am working on some longer form content some projects some view J s view X stuff some react stuff some some Django laravel so stay tuned for that is just taking me a little while to get to get some stuff together and to get some some dealings in order in my personal life and you know if you guys watched my last video tells you a little bit of what's going on but thanks for watching hopefully you like this if you did please leave it a like and I will see you in the next video
Info
Channel: Traversy Media
Views: 894,860
Rating: 4.9312935 out of 5
Keywords: async javascript, callbacks, javascript callbacks, javascript promises, async await, es6 promises
Id: PoRJizFvM7s
Channel Id: undefined
Length: 24min 30sec (1470 seconds)
Published: Fri Jun 22 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.