Async JavaScript - Callbacks, Promises, Async/Await

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Here is my latest video. In this one we'll go over JavaScript callbacks, promises, and async/await. I hope this helps at least 1 person. I appreciate any and all support. Don't forget to SUBSCRIBE! Thanks!!

👍︎︎ 1 👤︎︎ u/codeSTACKr 📅︎︎ Sep 06 2019 🗫︎ replies
Captions
in this video we'll go over JavaScript callbacks promises and async await thanks for checking out this video if you're just starting or even thinking about starting a career and web development you're in the right place I upload new videos every week hit subscribe in the bell to get notified let's first understand the difference between synchronous and asynchronous so synchronous operations in JavaScript executes one at a time this means no matter how long the current operation takes subsequent processes won't start until the previous is completed asynchronous operations run at the same time as other synchronous operations and then it completes at some point in the future so a great example of an async operation is an API call it may take a few seconds for the data to be returned and we wouldn't want our website or application to freeze while it's waiting on the data operations in JavaScript are traditionally synchronous and they execute one at a time from the top to the bottom so here's an example here we're logging the process of making breakfast so we have our coffee toast and eggs so I'm going to hit save and here we see it's logged coffee toast and eggs in that order so it actually takes a bit longer to make coffee so let's tweak this a little bit we're going to wrap this in a set timeout and we'll set that to three seconds or 3,000 milliseconds and let's take this coffee and put it in here so this will demonstrate it taking a little bit longer for us to make the coffee so now let me save this and watch the console.log toast and eggs pretty much immediate and then after three seconds we have our coffee so why did this happen well the set timeout function makes the operation asynchronous by deferring to the remaining coat the entire operation doesn't pause for the three seconds it continues and then it comes back to the coffee when the timer is up now one important thing to keep in mind before we go any further is that JavaScript functions are first class objects and that means that they have the ability to be assigned to variables to be treated as a value they can also have other functions within them and they can return functions to be called later so now that we have those concepts out of the way let's start talking about callback functions so when a function accepts another function as an argument this argument is known as a callback function the callbacks are a fundamental part of the functional programming concept and you can find them in most JavaScript code such as this set timeout so this function here within set timeout this is actually a callback another example of this is map so let's get rid of this and we're going to create a variable and call it names and this is just going to be an array and we'll say John Mary and Bob okay and then we'll create another constant and we will name it greet and this is going to be equal to names dot map so we're going to use the map function and here we'll pull out a name we'll use an arrow function if you're not familiar with arrow functions I have a video on that I'll put a link in the description below if you want to check that out and then we'll use template literal and we'll say hello and then the name so in this example we use the map method and this iterates through the array list and the method accepts a callback so this function here is our callback okay so now let's log greet console.log greet and we'll see that it returns an array that's been altered and it has added hello in front of every name so callback functions can be named or anonymous functions so far we've only used anonymous callback functions so let's look at a named callback function so we'll get rid of this and let's create a function here and we're going to name it greeting and we will pass it a name and then we will just log a template literal again hello and the name okay so we have to call the function so we'll just say reading and we'll say John alright let's save that and there we have hello John so this function is considered a named function it's named reading and we can actually rewrite this we could turn it into an arrow function by assigning it to a variable so greeting equals and then we have our named argument and our arrow and then we're just logging so we just need one line here and we'll say console.log template literal hello name okay so this one line is equal to these three lines here so let me comment that out and I'm just going to add an exclamation mark there so we can see it in the console and let's save now we have hello John exclamation mark so now we have this function it's a named function and we can use it as a callback in another function so let's get rid of this and this and we'll create a constant here of user info and that's going to equal first name last name callback and our arrow function within this will create a constant of full-name and that's going to equal a template literal of first name and last name and then we have to call the callback so we'll call back and we'll pass in the full name so this function simply combines the first and last name and then it uses our callback so in order to call this we will use user info and then we'll pass it a name so it will say John Doe and then we'll pass our callback function which is greeting all right so let's see what this does now it says hello John Doe so notice the usage of the callback here we're not using parentheses to define it as a function we're passing it as an argument and so we're not actually calling it here we're just passing it to the other function and this function the userinfo function is actually calling it so the callback function would never actually run unless it's called within the containing function now so multiple functions can be created independently and used as callbacks and these will create a multi-level function and when you have too many of these nested functions the code becomes impossible to read and this is known as callback hell let's take a look at an example here okay I'm not going to type all of this out I'm just going to paste it in here and so we'll try to go through this it's painful to even look at so we see we have a do something function and this is passed a function with the result and then within that function we have another function that does something else with the result and then it is passed another function with a new result and then we have a third thing that does something with the new result and then it passes a final result to another function that console logs got the final result plus the final result then after that we have to start closing and we have to add our failure callbacks for each one so you can see how confusing it is to pass each function as callbacks callback functions are useful for short asynchronous operations so when you're working with large sets of functions the callback method is not considered to be the best practice because of this promises were introduced to simplify things so a promise is exactly what it sounds like it's a promise to do something if something else is true and if it's not true then it won't so a promise is used to handle the asynchronous result of an operation with promises we can defer execution of a code block until an async request is completed this way other operations can keep running without interruption a lot of modern JavaScript libraries use promises so it's important to understand how they work now promises can have three states pending fulfilled and rejected so let's look at how to create a promise so we'll start with a variable and we'll name it promise if you name it whatever you want we'll make it equal to new promise and it has to have a capital P there and within a promise we always have two callbacks will have a resolved and a reject we'll put our arrow here and then here's where we can do stuff okay so let's turn this into something that will work so I'm going to add another constant here of has meeting we're gonna make that equal to false and we'll rename this constant to meeting and so this is going to be a new promise and it's going to check to see if as meeting is false so if not has meeting or if has meeting is false then we're going to create a constant and we'll name this meeting details and we'll make this equal to an object and the object is going to have the meeting details will say the name is marketing meeting and the location will be on skype and the time will be at 1 p.m. all right now after that we will need to do something with these meeting details so we're going to resolve the promise and we'll pass it our meeting details and then if as meeting is true I'll say else so if there's already a meeting scheduled we're going to reject the promise and we're going to pass it a new error and we'll say meeting already scheduled so if has meeting is false will create the meeting if not we'll return our error so we've created the promise now how do we use it so we'll chain dot then and dot catch to our promise like this so we'll call it by saying meeting that was our promise and we'll say dot then and we'll pass our result into an arrow function and so in here we'll have the resolve data and then after then we can use a catch and within here we will have our error and in here we will have our reject data so let's do something with this data so let's just log it so we'll do a console log and we'll say meeting scheduled and then we'll also log the result and then in our catch we will console log our error message all right so let's save this now we see meeting scheduled and we have our object so again in the then we're receiving the response from the resolve which is our object and then in the error we would receive our error message if there was one so let's go up to has meeting and let's change that to true and I'll save that and now we see meeting already scheduled so our reject error message is getting passed here in our catch now sometimes we may need to execute two or more asynchronous operations based on the result of the previous promise in this case promises can be chained so we'll use this example that we have here I'll change this back to false and let's create another promise so after our meeting promise I'm going to create another constant and I'll name this add to calendar and we'll make this equal to an arrow function we'll pass it meeting details and then we'll return a new promise and we need our resolve and our reject and within this new promise we'll create a constant called calendar and we'll just make this equal to a template literal and we'll say meeting details dot name is scheduled at meeting details dot time on meeting details the location so now we have to do something with this variable so we'll resolve the promise and we'll pass it the variable calendar this is quite a bit of code so we could actually rewrite this we could shorten it so let me show you the difference here I'm going to copy this and duplicate it so there you can see the the two and so what we could actually do is we can remove the promise statement from here let's move all this back so we'll still have our calendar variable but instead of doing this resolve calendar here we can simply say return promise dot resolve and pass the calendar variable so if we're going to go straight to a resolve we don't actually have to type all of this and create a new promise just to resolve it for one variable we can just create our variable and then return promise dot resolve and pass the variable so let me get rid of this one so now we have our meeting promise we also have our add to calendar promise so let's look at how we can chain these together so in order to chain this we simply have to add another dot then and that's it so let's run this and see what we get so now we get meeting schedule marketing meeting is scheduled at 1:00 p.m. on skype so we're getting this console.log here and we're getting this console.log with res now last time res was our object this time it is what is returned from the previous promise so in our add to calendar we're returning this template literal string so we can keep chaining as many things as we need to call multiple promises a lot of times we have multiple promises that we need to run at the same time and then do something once they have all completed in this case we can use promise dot all let's see how that works so I'm going to create a constant and we'll name it promise one I will make this equal to promise dot resolve and we'll just say promise one complete then I'll create another constant and I'll name this promise too and I'll make this equal to a new promise and we need to pass in our resolve and reject and then our arrow function and within this we're going to use a set timeout and we'll set this to 2,000 milliseconds that's two seconds and in here we're just going to resolve promised to complete okay so first let's see what they do on their own so let's do promise one dot then and we'll pass it the result and arrow function and we will just console.log the result and then promise to the same thing alright let's save that and see what happens immediately we have promised one and then promise to after two seconds so that's exactly what we'd expect but we want them both to return at the same time so in that case we'll use promise dot all so we'll say promise dot all and then in here we'll pass it an array of the promises so we'll say promise one and promise too after that we'll have and then and our result and we'll console.log the result okay so let's comment these out and let's run this and watch after two seconds we get both of the resolved promises in an array so a quick side note there is another method that we could use that is promise race so I couldn't think of a good example for this but if for some reason you have multiple promises and all that you care about is the first one that finishes and the rest of them you want to discard we could change this to promised race so this is only going to return the first promise to finish so immediately we're going to get promised one complete and it's not ever going to return promise - okay so just to recap what we have so far promises still use callbacks but they are easier to read and write they provide a way for us to continue our code while it waits for something else now there is a special function that you don't often hear about and it's called a generator function so let me show you what that looks like okay so this is what a generator function would look like so what makes it a generator function is we have this star here and then we have this keyword yield so we're getting some data and we are pausing the function until we receive the data and then doing something with the data so generator functions are not about asynchronous operations or event loops they're just about pausing things and so with this you can pause just this one function while the rest of the code around it continues to run so generators are complex and we could spend an entire video on them so I just want you to understand where generators fit into the next subject that we're going to cover which is async await so async await is basically just a thin layer of syntax on top of promises and generators it can be referred to as syntactic sugar it just makes writing promises easier and look better so let's go back to our meeting example and so what we can do here is we can turn this into an async await function so in order to do that we need to wrap our promises in another function so we're going to add before this a function and we'll name it my meeting and what we need to do with this function is we need to define it as async so we add that to the beginning of the function now within the function that are calling the meeting and then calling calendar and then doing this and catch this we're going to actually get rid of all of this and we're going to create some variables so we're gonna say Const meeting details equals a wait meeting okay so this is going to assign the results of meeting to the constant meeting details and we added the await in front of our promise so any code after meeting is not going to execute until meeting has finished so the next one we'll add is constant message and this is going to be our calendar message and we'll say oh wait add to calendar and we're going to pass it the meeting of details so this promise add to calendar needed meeting details to complete first so that's why we have the await and now we're going to await on this one as well so nothing after this will execute until it's completed and so what we'll do is we'll just console.log the message and so we'll have to call this function so we'll say my meeting and just call the function so let's see what that does and we get our marketing meeting is scheduled at 1:00 p.m. on skype we get our message so you can see how this is much shorter and more concise easier to read it makes it look a lot more logical in the order that it's executed so now you may think well what about error handling because we took away the catch so where is the error going to go so let's go up to the top and let's change this to true and let's save that and so now we're getting an uncaught error we don't want that so with async await functions there are a couple of ways that we can go about handling the air so for a one-off or a unique situation we could add the error handling when we call the function so we could use a dot catch here and then do our error-handling and then I'll save this and we have our error now you most likely are not going to want to do your error handling on each call so another way to go about this is to put our entire code block here that any code that could possibly throw an error we want to wrap it in a try-catch so we'll say try and then catch and then within the catch we can console.log our error message and I'll save this and you'll see that we get the same thing so now this catch is passing our reject error message to the console okay so that's going to be it for this video if you made it to the end thank you for watching if you have any questions about any of this add a comment below and if you think this video or any of the videos on my channel might be helpful to someone else please share them as always if you liked this video a thumbs up is appreciated I upload new videos every week so hit subscribe in the belt to get notified i'm also on twitter and instagram at code stacker thanks for watching
Info
Channel: codeSTACKr
Views: 36,451
Rating: 4.9797339 out of 5
Keywords: callbacks, javascript callbacks, javascript promises, async, await, javascript async await, async await js, async await javascript, js async await, javascript async, javascript await, async await, async javascript, js promises vs async await, javascript async await tutorial, async await tutorial, js async await tutorial, js async, javascript, javascript tutorial, async programming, js promises, es6 promises, promise tutorial
Id: F8xANXY0kaU
Channel Id: undefined
Length: 25min 10sec (1510 seconds)
Published: Fri Sep 06 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.