Ah the new feature in javascript that everyone is talking about lately 'Async Await'. In this video
we're going to learn what all the hype is about. To get started
You must first know that Async Await is part of ES8 and is built on top of promises.
If you aren't sure what promises are.
Make sure you check out that video first.
Now underneath the hood an async function is a function that returns a promise. But the benefit of Async
Await is that it makes code easier to read.
Let me show you what I mean.
This is a promise that we just made up.
It's a move player function.
Imagine we're designing a game and it has the distance plus the direction that the player moves and
if we want to change these we have 'move player' '.then', 'move player' again, 'move player' again.
'move player' again.
Now this is asynchronous code.
We know that move player is going to happen, then
This is going to happen, then this, then this.
If we want to have any sort of action within here we can wrap it in brackets and console log that extraction.
All things that you can do with promises. with async await
It would look something like this.
What's going on here.
The big benefit of async await is that it makes code easier to read and I know you're probably not thinking
that right now because this is new syntax but just give it a chance.
The goal with async await is to make code look synchronous - a code that's asynchronous look synchronous.
Now if you remember a promise in javascript is kind of like an 'I owe you'.
I promise to return something to you in the future.
Something like an AJAX call resizing an image getting some information from a database.
These are all things that take time.
Instead of waiting around on them we want to continue on with our lives and just have it
Let us know when it's done.
But we're going to keep working on our own stuff whil it's doing that in the background.
We do it this way because that is how javascript works.
If you remember in our "How Javascript Works" video we talked about javascript being single threaded. For
our programs to be efficient we can use asynchronous programming to do these things.
So promises help us solve this and it looked like this.
Now remember what I said at the beginning async await code are just promises.
Underneath the hood we call this syntactic sugar something that still does the same thing but is just
different syntax to make it look prettier.
Syntactic sugar. And promises have this .then that you keep having to chain async on the other hand
has this async word in front of it and some await key words.
So let's go through what all this means.
Although these two things do the same with the playerStart function.
We first declare a function as async. We lead javascript know-
"Hey this is an async function." And we declare it with the word function and then a function name.
We now can do anything we want inside of this function but we have access to a new word because we used
the async word to define this function.
We have the 'await' keyword and this keyword says- and we can remove this for now.
This 'await' key word says "hey pause this function until I have something for you."
So we're awaiting the response.
And you can use this 'await' keyword in front of any function that returns a promise which we know that
move player does.
And once the promise is resolved then the function moves to the next line and it awaits the next move
and awaits the next move and awaits the next move.
Now the cool thing about this is that instead of chaining it like this I can now assign just like asynchronous
programming, variable first to await this and I can assign second
to await this and first and second will have the result of each function but in a variable.
So it looks very synchronous.
You're not using '.then' you're not chaining.
You just have simple synchronous programming you're waiting for this to happen.
Then waiting for this to happen.
But let's use a more realistic example so we really understand this.
If we use our fetch function and again if you remember fetch function.
That's a promise.
You see that we get a promise.
So with the fetch function if we use our favorite API resource, json placeholder. Let's grab the users
here so this users end point. If we want to fetch something we did return a promise so we would do a
.then
response we would have to run it through.
json
And then finally .then console.log the response or the data that we get.
So again if I copy and paste this into our console, we get a promise that's pending initially then it gets
resolved and I get my users.
Now how can we turn this into an async function.
Again the same feature will work the same but it will look a little bit cleaner.
It will be syntactic sugar.
Well if you remember we have to declare a function with async keyword and this function will say
fetchUsers and fetch users
Will have this inside of it.
But we can now use in front of anything that returns a promise.
The 'await' keyword.
So now this function is going to pause until we get a response from fetch.
So I can say const 'response'
equals await the fetch call. And now instead of using the .then I can say const 'data' equals 'await'
'response.json()' because again 'response.json' returns a promise so I can put the 'await' keyword. And
then finally I can just 'console.log(data)'
All right let's copy and paste this and see if it works.
All right.
Now I call the fetchUsers function which is the async function.
And I made a bit of an error here.
There's no response it's 'resp' short form response. There you go let's try that again.
So let's refresh that.
Copy and paste, run the fetchUsers function and look at that.
We have our promise that got resolved.
And we have our users nothing different from the promise but now we have a nice step by step
looking code that says fetch this.
Get a response, then run it through the json method and then console log 'data'. And you might be thinking
to yourself is this actually prettier than what we had before.
Let's remember what we had before.
This is what we had before.
This is what we have now.
And some of you might argue that the first promise way it looks better.
And you know what.
It's personal preference and this is a simple example.
So there are times where this actually looks a lot cleaner.
But I'm a big believer in doing what's easiest to read and understand for you and your teammates.
Let's do one last example. Let's do something even more realistic.
Let's say that we have a list of URLs and this time we have the users, posts and albums from the
json placeholder API.
And we want to run through them all.
If you remember in our promises video we had something like this.
Let's remove this so you can see it better.
So we had something like this.
We did promise.all - we mapped through the URLs. We fetched the URLs and responded with the JSON
and then we returned the array and the array had users, posts, albums and we also did a .catch.
So again just to make sure that this works going to copy this put it into our console and we see that
we get our users, posts and albums data.
So that's working.
Let's convert this into an async function.
Well let's start by doing a 'const getData' and this will be (equal) an async function.
And I want to just point out that I did it this time with the function expression instead of the way that
we did it last time which was async function and then the function name.
But I just want to show you both ways.
All right so how can we do a 'promise.all'? Well if you remember we can now put the 'await' keyword
in front of any promise. So we can put the 'await' keyword in front of promise.all
So I can say that const- and this is a little ES6 magic of destructuring- I can say users, posts and albums
that We're going to receive is going to equal 'await' and then the promise.all which we already have.
So let's just copy that.
We're going to copy the promise.all and place it on here.
All right.
And now we can just console log what we had. We can copy and paste right after we 'await' all the promises
we'll have 'users', 'posts' -if I can spell. and then 'albums'. and instead of Array because we've done it with destructuring
we can just say 'users'
'posts'
and 'albums'.
All right so let's see if this works. Copy and paste this and run getData
and look at that.
We got the exact same results.
Very cool.
But there might be one thing that you noticed here that is in the promise way we have the .catch.
If any of these fail we want to catch these errors how can we do that with async await.
Right now we're not catching any of these errors.
This is the part that not a lot of people are big fans of.
But it is something that once we get used to it's not too bad. JavaScript has something called 'try catch blocks'.
and that is when it sees the 'try' word it's just going to automatically run whatever's inside of it.
In our case all of this block we want it to run in a try block and then 'try' comes with a catch block
as well.
So a try catch block and within the catch if anything fails within here.
Well we can catch it in here so we can just console.log
'oops'
So now let's say I misspelled one of the URLs and let's copy this. Let's try it out.
We'll have the new URLs.
Let me clear that. New URLs with the misspelled URL for one of them.
We're going to copy and paste the getData and you'll see over here that we get a syntax error.
And that is because one thing you have to remember with catch is that the catch receives an error and
this error you can console log it
if you want. So let's just console log and then try this again.
This time we'll just call this one getData1 -perfect.
Now if I clean this up a bit and do getData1 with the try catch block I get
'oops'
Type error failed to fetch.
So I get the catch block with the error just like we did with promise.all just using promises.
And there you have it.
That's it.
Async await although intimidating at first because there is a bit of new syntax actually makes things quite
nice and synchronous looking.
We simply have a variable that we assign the await promise to and then the function pauses there
until the promise returns and then it continues on with console logging.
And you just have to remember the try catch blocks here to catch your errors and that's it.
You're now an async await Master.
You can use whichever one you prefer.
Like I said at the end of the day use promises or async await functions based on whichever one is simpler
for you and your team but hopefully when you encounter both of these, you're now a lot more comfortable.
I'll see you in the next one. Bye-bye.