Transcripts
2. What is the Event Loop: Are you ready? I hope so. This is awesome section and Awesome glass and
awesome few lectures talking about async and await. And this really is adding a modern flee to the
already modern It's API. And I hate that word, but in order to understand
async and await, you need a high
level understanding on what the event loop is. I don't want to get
into too much detail on the event loop that you
need to know it exists. And it will just help solidify
asynchronous requests. Or at, let me start
right at the basics. We know that the browser, aka Chrome and JavaScript, for example, Node.js,
they are single threaded. And because we're
dealing with ajax, I'm more concerned right now about the browser and get this, everything inside a browser
runs off a main thread. All browsers have a thing
called a main thread. And on this main thread, loads of things happen. This is where the parties
it for the browser. This is where your
JavaScript code is executed. It is where the rendering
happens and it's way the DOM, the Document Object Model loops. What does this mean? It
means that if something on the main thread takes a
long time to execute, everything else is
going to be blocked. I want you to visualize
this picture. They've being a main thread. On this main thread, everything happens
like I mentioned, this is where the parties yet. It's not only JavaScript is
executed in the main thread, it's also the
updating of the DOM when a browser updates CSAs. This all happens on
this main thread. To avoid certain tasks
blocking everything else, the browser came up with a
very good idea of spawning multiple threads away
from the main thread. But of course, once
these strains have done something that a page
needs to care about, they need to come back to
the main thread to give the browser that information and weight as the event
tube foot in. Do you know? Well, it is the event loop that handles and manages
this entire process. Come on, That's
pretty cool, right? That is the even tube. And to drive the point home, why don't we look at
code specifically. I want to look at the
setTimeout function. We've seen it a few times
in this course already. But let me break it down. This is how you write it out. It takes two arguments, the callback and milliseconds. But what does the
sake timeout function mean? What is it doing? What it's doing? Two things. First thing is that it waits x milliseconds
whenever we define. And once it's done, waiting
for those milliseconds to pass is then going to execute
the callback function. But let's now not treat this
as an asynchronous function. Let's now pertain that the setTimeout function
runs synchronously. If we executed it like asynchronous function,
just like us, it would run on the main
thread and this means it will pulls everything else
until it's done. We don't want that
to happen, right? That's very poor for
user experience. How do we solve this? Well, That's right To avoid this state timeout function is not run on the main thread. Remember those side trades. A fancy development
term for that is that it's being run in parallel. And that's just fancy talk for
off the main thread on one of those side threads that if you really stop
thinking about it, this is going to pose
another problem because when it comes time to execute
that callback function, remember, after the milliseconds have passed, then what happens? Well, that callback function
has to be executed and way is the execution
taking place. That's right on the main thread. Can you see the problem with
that automatically going straight into the main thread whenever they call that
function is ready. The problem is that
you could be running a lot of JavaScript
code in parallel. This means that
potentially you could be editing the same DOM
at the same time, NG day full run into
what developers called race condition problems. Effectively what that
means is you don't want one JavaScript function
half manipulating the DOM. And then suddenly this callback
function gets thrown into the main thread and starts executing another
part of the DOM, or even worse, overriding what the first JavaScript
execution function was doing. How do we solve this problem? Well, the browser, again, is very clever to ensure
that you don't run into problems with executing multiple JavaScript
code at the same time, task cues were introduced. I know what you're thinking, you're thinking client
development is hard enough. Now when we're talking
about event loops, we've got terms
like parallel off the main thread side
trades task queues, but just doesn't stop. Don't worry, don't worry. I know I've been there, but it really does
make intuitive sense. If you just take a step back, you've got that main thread. Can throw everything at the main thread at the
same time they fall. Functions, tasks
have to be queued. So this really does make sense. Just remember, a key part
of how the event loop works is the concept
of task queues. And how did these
task queues work? Well, what the browser
does is it tells the oven tube that it has some functions at wanted to do something on the main thread. And your browser's going
to add that function to the task queue when that
function is ready to execute. Basically when the
function is ready, it gets added to this
task. You, it's waiting. And only when there's a gap in advantage people to be put
back on the main thread. This ensures that things are executed in an orderly manner. It makes sense because
eventually the vent loop, we'll get to executing those
tasks when it's ready. Then let's talk again about
our sit timeout function because we know the
setTimeout function is actually an
asynchronous function. How does it look in reality? Well, again, we'd write it
out exactly the same way. Again, two things are happening when we
execute this function. But this is what's
really happening. One, we've got a
weight x milliseconds, but this is being
run in parallel. You know what that
means? Not being run on the main thread. What's the second thing
the browser does here? It will queue task when
the callback is ready. Once we've waited a certain
amount of milliseconds, and that callback is
ready to execute. The browser will
edit to the task. Of course, the event
loop will invoke the callback function
when it's ready. When the event loop is ready. I'm just going to blow your
mind a little bit more. This is getting very advanced, or perhaps could
have stopped here. But you do need to
know that they're all different
categories of tasks. We've got microtasks
and microtasks. I guess a good way of thinking
about it is you've got important tasks and not
so important tasks. What does the macro task? We'll tasks in the
macro task queue, like the sit timeout function. Then you have to wait
for the next round of the event loop before
being executed. Another way of saying it
is that the tasks and the macro Q processed
one item at a time. However, tasks in
the micro task queue will be run in the current
round of the event. Another nuance is that micro queue tasks all
process to completion, including any items,
any functions, and the additional code you add to the queue in real-time. And because of the high
importance on microtasks, that means the event
loop is going to block rendering while it's
executing microtasks. Client, okay, client, I get it, I get it, but where does
ajax fit into all this? Well, we know that ajax
deals with promises. Promises of very, very important when it
comes to browsers. This means when the code is eventually edit to the
main thread to execute. Let me say this. When the browser adds those callback functions
to the task queue, it treats these functions
as micro tasks. I know, I know. Probably
blowing your mind. Don't worry. You don't strictly
need to know about all of this in order
to understand ajax. But it's very, very interesting
and advanced concepts. It's fun. And I want you to
be a grandmaster. In the next few lectures, I want us to now hop to the
console and I want to start looking at how the
vein to loop works. I wanted to write
some code with you and talk about my
ideas about what's happening in the background really is going to
drive the point home. And then of course
we're going to jump into what async and
a weight really. I can't wait.
3. Macro Tasks vs Micro Tasks: Welcome, welcome, welcome. I'm super excited. I hope you dancing. I hope
you're having a lot of fun. I hope you're learning a time. And thank you so much
for sticking with me. We really have come a long way. And of course we're getting
into video farms topics now. We have been discussing
the event loop, but what is better
than showing you? I know nothing, which
is why I'm gonna show you the event loop in action. That's going to be
quite interesting. Strictly speaking, I don't
have to show you this, but I want you to become
a grandmaster encoding. I don't just want you to
understand basics of Ajax. I want you to understand what's happening behind the scenes. Of course, we're gonna be
discussing async and await. But in order to
understand async await, I just want to pause a bit more knowledge
about the event loop. Remember one of the
important things with the event loop is the
concept of task queues. Functions, methods, to-dos
or edit to a task queue. And of course you get
different types of tasks. We get macro tasks and
we get microtasks. But Clyde, we already
know all of this. I know you do. So why don't we just play around
in a text editor? Why did we have a bit of fun? Here we go. I've got a blank Visual Studio
Code editor open. I've got one file called
test.js. That's it. Now, I could just
open the terminal, we could just console log
everything to the screen. We could execute our
JavaScript in the browser. There are many ways to do
something in programming. I'm going to show
you yet another. Now I want to implement the debug mode in
Visual Studio code. So I'm just going to
click on that tab. And I'm going to
click on this, create a launch dot JSON file. And let's use Node.js to taste. Of course, Visual Studio code automatically creates this
launch stop JSON file. I don't want you to
stress about all this. You don't have to know
how it all works. Or I'm wanting to get to is this debug console that's
very, very useful. What do I want to
do? Well, let's just console log something to the screen to start off with. And I don't know, let's just
console log console one. How's that? But what's nice with us? Debug environment as you can put breakpoints in your code, you can step into your code. Very useful. But anyway, here I'm just
going to run this code. And in our debug console
we see the results. It's console one. That's a watered by the way, my favorite push animal. There we go. What do I want to show you? Well, let me ask
you this question. Instead of cooling it console, I don't know, just cool it. I didn't know synchronous
because we know the function console log
runs in asynchronous way. If we have two like this, right? What do you think will
happen? What do you think the result will be in
our debug console? Let's write, we
know JavaScript and Node fit meter is
single-threaded. We know the first line
will execute synchronous. One in the parcel will go on to the next line
and net will execute. All right, so let's run it. We got exactly what
we would expect. It's thought getting
a bit more funky. Let's add a macro task. Remain macro task. For example, the
setTimeout method, macro tasks we know
or edit, toss, queue and executed the mixed
brown of the vinculin. That's what a macro task is. And we know setTimeout method,
which is asynchronous. It is a macro task. I'm just going to use shortcuts. So it's very easy to read. And all I wanna do is
I want to console log. I don't know, let's
say timeouts. And we can have a
picture of a giraffe. And we know the
second argument to the sixth timeout function is how many milliseconds
we want to wait. Well, in this case, let's
say Sarah milliseconds. Very simple example. Now I want you to think What's gonna be the result
in our console. What's going to happen
if we execute this code? Let's run it. It's pretty much what I'm
sure you were expecting. The first console, it
runs on the main thread. Now we get to the
sit timeout method that is added to the
macro task cute, aka it's being run
off the main thread. Of course what that means, even though we want to console log the results of that
timeout immediately, it's still off the main thread. And while it temporarily
resides off the main thread, we get this console log, which again gets executed
on the main thread, which is why console log
synchronous one happens first, console log synchronous
to happen second. And then finally,
almost instantaneously, let's say timeout method, edit back to the main thread
and then it gets executed. Interesting. But now, why don't we
deal with promises? Remember, ajax is
all about promises. And we know that promise
is not a macro task. A promise is a watt. That's right. It's a microtask. And we know they are edit to the micro task and they
are executed before. This is the key difference
between microtasks and macro tasks are executed
before the start of the next. Why didn't we use the promise object and we
execute its resolve method? Of course, in real life,
you'd have a whole lot of code and then execute
the resolve method. Then of course, let's execute
our callback within a dean. We don't need any arguments, so we can just console log
something back to the screen. In this case, why don't
we just grab our giraffe? Instead of calling a timeout, we can call it promise. What do you think
will happen now? This is getting a bit trickier. You need to think about it. What order would you
expect to see things? I would expect to
see synchronous one, that console.log that
first one on line one. That would happen
instantaneously. Now what's interesting is
that the setTimeout we know is going to be edit
to the macro toss Q. The pulsating is going
to go to the promise. And when it hits that promise, a promise itself will
be on the main thread. But when the pulses sees the lean method that will be executed off
the main thread. In fact, it's going to be
added to the microtask cute. The possible then hit
the lost console.log. The synchronous to line would show because that's gonna
be executed immediately. So I would expect
synchronous one, synchronous to show first, because the promise statement
is on the micro toss Q out to expect debt to be
issued back to us first, the giraffe promise, then
finally the giraffe timeout. Let's see if I'm right. Let's hit the Run button
and let's see what happens. Exactly what we would expect. Super, super interesting. Can you see how fun this is? Can you see how intuitive
this all becomes? Okay? This is just a warm up. I want us to take a break here. In the next lecture,
I want us to get more advanced, not
cutting it at that. I want to start creating
our own promises. I know exciting. I want to use a while loop
so we can kind of see how it blocks execution or injuring
of other functions. And it's gonna be
super fascinating. This was just a warm-up. I'll see you in
the next lecture.
4. Creating our own Promise: Welcome back. Hope you're having a lot of fun. And like I mentioned, this
gets more complicated, so let's delete everything. Oh, man, I hate deleting
all my beautiful work. Anyway, let's continue. What I wanna do is
I want to implement timestamps throughout our code. Now, just to show you
how to do something new. In order to do that, I want to start with getting the time right now before
we execute the code. It's very easy to
do in JavaScript. You can just excess
JavaScript's date object and execute the
nominated. Very simple. Next, I wanted to
create a function that console logs something
to the screen. I don't want to be writing
all the time. Console log. Implement that in a function. So why don't we create
a function and call it output for lack of a better word because
that's what an output. It's going to take an argument. Let's just say for
lack of a better word, that can be what
we pass into it. And what do we want to happen? Well, like I mentioned, I want to implement a console
log function. Simple. What do I want a console log? Let's put this in template
literals want to console log. Firstly, whatever we pass
into the output function, I want to actually console
log that takes itself. The next thing I
wanna do is I want to implement a new line. Then I want to show how much time it took to
execute that function. I want time elapsed. In other words, that
is going to be what? By the way, the dollar
sign curly brackets inside temperature joules just
means that we can reference variables and write
JavaScript. It's very useful. So what we can do is
we can get the time right now after the
code has been executed, which is date dot. Now we resold it. We can deduct that from our mouth variable that we
defined at the beginning. You know what, Maybe it's
better not to call this now. Maybe I should call this begins because that's
our beginning time, just so it doesn't confuse you. I hope that's making sense. Let me just zoom out yet to slightly so you can see
it all in one line. We just finding the
difference between the time now and the time when we
started executing the function. Very simple. Let me zoom in slightly. What I want to do next. Well, I wanted to define
a blocking function. It's gonna be a very
simple function. Well, I want to do is I
want to create a loop. So let's define a
variable i starting at 0. And then I'm going to use
JavaScript's while function. This will execute all the time, provided that what's provided in this parenthesis is true. We're going to say
it's going to execute while I is less than, I don't know, just a
very large number. And then on each iteration or I want to do
is increase line. You can see we not
doing much. Oee. And then when it's
all done, when this while loop is finished, the code will then go
on to the next line. And then we can just
return something. What do I want to return? We can just return text. We can say done enough to
put a nice pretty owl. Yeah. I've got an owl in my
garden by the way, and I want to build an owl box. So excited. Anyway, I think that
looks pretty cool. All done. There we go. That's our blocking code. And now we've done, all I'm gonna do now is execute these functions and I want to ask you what's gonna happen. So firstly, let's see it. Our output function
we defined above. Remember we're going to
pause it in some taste. What tips do we want
to pass into it? Well, we can pass it
on ice, will talk, and then we can just
look at an asynchronous, which is what we did before, synchronous one, what
do I wanna do next? Well, I want to execute
our output function again, but this time as an argument. Remember we giving
it an argument x. I don't want to
pass in simple text. Well, actually I do. But I want to pass in our function which will
ultimately return. I'll take saying all that. In order to do that, we
can pass in the function, we can execute this
function blocking. Then finally, you guessed it. I want to do another
synchronous console log, but this time of course it. Alright. Let me ask you this question. In what do you think the result of this
code is going to be? What's going to be
displayed to us first. Well, I would expect
synchronous one to show first, That's right. D naught. Well, we've got
this blocking code and it's nothing
asynchronous about that. While loop in JavaScript
is very simple, it runs on the main thread. So when the parser,
when the agent hits this wild function
on the main thread, it's going to stay
on the main thread. And everything else is
going to have to wait. Boring. I know this is
bad user experience. Then finally, when that
while loop is finished, we get to the final
output synchronous tool. Let's see if I'm correct,
that's launches runners. And look at that. Synchronous one time
elapsed was 0 milliseconds. That's how quick it was. We get onto this
mixed while loop, You know what 80
milliseconds is also but, but short water and
add a few more zeros. Let's run it again. Just to make it a bit longer. We get synchronous
one and then it elapses and we finally
get to synchronous. Two very interesting,
Very interesting. I know, I know. That's why I wanted to show you. But now I want to pose
you another question. How do we stop
this blocking code from happening? How
can we stop it? How can we turn this into an
asynchronous piece of code? What do you think? Remember what we wanna do is I want to create a
separate thread. I want to get off
that main thread while that while
loop is running. And of course we net
while loop is finished. I want to add that return
statement to the microtask. Cute, That's what I want. How do we do it?
You might think, yes, we can create a promise. You might be correct, depending on how you thinking
you strike this promise. Let me show you what won't work. So let's just comment this out. Now we should actually
call it unblocking. For lack of a better word. How could we do this? Well, you might think, let's just return
a new promises. It's execute JavaScript's
promise object. We know that it will give us back resolve object
and a reject object. We know this from
previous lectures. We can execute our callback
within these curly brackets. You might think that we can implement our
while loop here. I equals 0. Implement while. How many zeros do we
do this? Just copy it. While I is less than
whatever that big numbers. Well, we want to do
is increase I by one. When it's finished. We don't want to
return anything. What do we want to do
is we want to call the result method
and resolve method. Of course, we can just
have this saying hold on. Okay. Are you with
me? Sorry, false. So we've tried to let's
actually delete this. We've tried to convert
the blocking code to unblocking by
implementing a promise. You know what they mean? Get
rid of the capital again, my OCD, not a
constructor function. So let me do a lowercase u. You might think that we've
implemented in our promise. This promise happens
off the main thread, and therefore everything
happens as we would expect gonna be unblocking. Now, you might think synchronous
one will show first. Then, because the unblocking
code is off the main thread, we should see synchronous two. And then finally,
when it's done, we should see the result. All done. That this is not going to
happen, will it shouldn't? If I'm thinking correctly, let's launch this program. Let's see what this happened. There we go. So you saw that actually, even though we're trying
to execute a promise, it's still blocking
the execution of our next synchronous output. That's why we only
get to synchronous two in 143 milliseconds. A so weird, Clyde,
I'm so confused, I thought because we
wrap this in a promise, that means that we will execute this entire code off
the main thread. It can get very confusing. But now there's something very advanced I wanted to share with you. Are you ready for it? So it's going to blow your mind. Just remain but the
actual creation of the promise itself and that
execution of the while loop, which is happening
in the creation of this promise that is still
happening on the main thread. Here's the thing. Promises themselves are
just monitoring tools. They are not actually
asynchronous themselves. Weight is asynchronous, fit
in when it comes to promise. It fits in. When we execute the
vein statements. When the engine sees
a Dane statement, it takes what's ever inside the theme statement off the
main task of the main thread. And only when net
result is ready does it get added to the micro task. In other words, it is only the resolving
of the promise in a vein statement that happens off the main
thread as a microtask. Very, very fascinating. So that's why the first
synchronous console log line gets executed right away. That this second
synchronous log only gets executed off
the while loop is done because the creation of that promise is still
blocking the main thread. I'm sorry, I didn't mean
to keep repeating myself, but this is such an
important concept for you grasp and it's
going to help you. Then let me ask you this. How do we then no pun intended. How do we then solve this issue? How do we ensure that that while loop is happening
off the main thread? Well, of course we
want to execute the resolve method and then put it all within 18 statement. We don't even need this reject property because
we never use it. In fact, I can delete
this entire thing. We can immediately execute the resolve method
on this promise. We know in it's executed, the engine's going to look
for the vein statement. And this is where
our code can lie. They may actually put a TIA. We don't need any arguments. It should work. I think we've got enough
brackets, they should work. Now the while loop is
within a Dane statement. We should expect this now to
happen off the main thread. It's now execute this code called type area promise
resolve is not a constructor. Of course, not only
the new keyword. Quite handy having
error messages there. Alright, let's go now. And there we go. This is awkward hand. Let's just see here we get
another reference error. Resolve is not defined. Of course I'm calling
the resolve method here. I actually just want to
return this because we within vein statement
drive, they'll city. Of course I don't
even need brackets. It's just pointless. Let's try this again. Sorry,
third time, lucky, Let's go. That's a notice we're not
getting our old done statement. Why? This? Interesting again, just
remember what we're doing here. We've created a promise and this promise return something. At the end of the
day, it's going to return a string saying all done. The problem we're having is we never accessing that return. Remember what a promise expects? It expects to give
us the result. And then we can exit that
results in a dean statements. So we actually have to call
out I'm blocking function. And then when we've
got that daughter, we went to execute
some sort of function. The function we want to execute here is that output function. We can just execute
that output function. This should work. It's a quick and dirty
way, but it should work. Output. Let's see if this works out. Let's now run our
code. We did it, We did it false time, lucky. Sorry about that, but we
got there in the end. Just remember what
it is we've done. I'm trying to show
you that a promise, the actual creation of a promise is done
on the main thread. It's only when we start hitting
these links statements, aka when the resolve
method is called. Do we then get off
the main thread? And that's where the
asynchronous magic happens. I just wanted to
make that clear. That's why here we
get synchronous one given to us back first, we get synchronous two
given vectors next. Then finally we get this
return statement of all done. By the way, you
might be thinking, why did I just put the
function name outputs? Don't I need to pass
in a variable x. It is pretty much doing
that behind the scenes. I could've been, if
argument's sake, we could have taken the data. In this case, it is
just going to be the text daughter all done. And then we can write it after the usual way that we
used to in this course. And then of course, execute that output function and
we pass in that data. So we could have
written a Titus. I just did a shortcut. If we run this program again, that should give us exactly
the same thing which it does. I know, I know this
is pretty advanced, well done for sticking with me. And you don't strictly
need to know this in order to work with
async and await. In fact, you don't
even need to know this when working with Ajax. But I want you to be
better than the race. I hope you've had a
lot of fun and I hope this is just ********
some more light on how the Vancouver works and
how asynchronous code works. In reality, they aren't two main threat doesn't work that way when it
comes to JavaScript. But at x lacquer does. If I could take things off the main task, you
put them back on. It's very interesting that
enough of the event loop now, I think you've got enough of a high-level knowledge about it. The next lecture, I
really want to start talking about async and await. We want to improve our
Fetch API faculty. I can't wait to see you
in the next lecture.
5. Intro to Async / Await: Finally, we are on the
topic of async and await. What exactly is it? Well firstly, we can
add async and await. These are just keywords
provided to us by JavaScript to reduce
our statements. Remember when we're
dealing with fish calls, with dealing with promises. And every time a
promise resolves, the first thing
statement will get executed inside that
thing statement. You need promise returned, will then look for the
next dean statement. So in reality, as we've seen, you can have multiple
vane chains. This can get quite confusing. Trust me, especially if
you've got very complex code and you've put a lot of
promises being resolved. A workaround is to use async and await that allows us to write
code in a synchronous way. Even though all these promises are happening in the background. Don't worry if you
don't know what I mean, I'm gonna show you shortly. The point I'm trying
to make is that using async and await
works very well with Ajax because you use async and await when
working with promises. And of course we
know that Fitch uses promises before we
talk about await. Remember the two keywords yet, async and a weight. I want to talk about async, not in-sync, not a sink. I love my dad jokes. I want to talk about async and putting the word async
before function. It means one simple thing. Don't get lost in
all the detail. Just means one thing. What does it, what does it
tell us? What is it doing? It's telling the function
to return us a promise. What weird, but there is nothing better than showing
you with a live example. Let's hop over to
the Text Editor now.
6. Async returns a Promise: If you know the drill, That's create a new file. Let's just call it for lack of a better word, messages ab.js. Because I'm going to create
a function called message. That's why let's create a
function called message. In order to do so in JavaScript, we just use the
function keyword. We can call it anything we want. I've called message. Then within these
curly brackets we define what we want to happen. Yeah, I just want to
return the word Hello. That's all I want to happen. Yes, I could execute
this in the browser. Then we can see the results. Why don't I just use coca? Ithaca allows us to run JavaScript real-time
in this text editor, it is very, very useful. It's free by the way,
my voice loved Mahila. Alright, what I want to do, let's console log this function. Yes, we would expect
the result to be hello, which is what you
seeing on the screen. That makes intuitive sense. But remember what I
said in the lecture. Async can be used before any function.
That's pretty cool. So what did we edit in
front of our function? Remember what I said? Using
async means one thing. Instead of function
will return a promise. So let's test it out. Let's put async in
front of our function. Now when we execute
this function, we don't get that text Hello, we get a promise. Isn't that interesting? That's all that it does. That async keyword
returns a promise, but Clyde, can't we just
explicitly return a promise? We can, instead of
returning Hello, can't we just return a price? What do they do? That gives us exactly the same thing that gives us a promise, of course this time That's not going to resolve
to the word Hello. We don't have it
in their animal. And so what we could do is we could execute
the results method. And on here we can
type the word hello. It's exactly the same as us
doing that by putting async, then we can get rid of async. We're gonna be getting
exactly the same thing. So instead of writing that
big long takes lie name, we can put the word async. And of course we don't need
now promising results. We can just return whatever we want returned from the promise. Is that making sense?
Are you with me? Sorry, fall. That's all
at the async word does. Async ensures that the
function returns a promise. Simple enough,
doesn't only do that. There's another keyword
I'm leaving out. And that is a wait. Wait only works inside functions
with the async keyword. Some thunder outside, it's
raining, it's raining. We needed though. We haven't had rain
in a few days. Anyway where it was on. Yes. We've only discussed async
that returns a promise. But in the next lecture, I want to start showing you
about the await keyword. I can't wait to show you.
7. Intro to the Await keyword: Hall, all good things
come to an end and a bit sad because I know we approaching the
end of this course. But don't worry,
we're not quite done yet. We're not quite done yet. And I'm always coming
up with new courses. So I hope we weren't
pathways here forever. But anyway, we are talking
about async and await. We looked at what the
async keyword does. Do you remember? That's right. Async ensures that the
function returns a promise. We could do this manually,
but it's just cumbersome. So async is just
a nice handy way for us to tell the function
to return us a promise. We know that. But now I want to
talk about await. The first thing is it only
works inside async functions if you try and use the word await in a random
function in some code, It's just not going to work. You have to use it
inside a promise, inside a function with
the keyword async. Await, do, I guess the actual
word itself gives it away. It makes JavaScript wait until their promise settles
and returns its result. Very, very intuitive. Take a step back though. Don't get lost in
all the detail. The purpose of async and
await is to simplify the syntax necessary to
consume promise based APIs. You don't have to use async await when you make
a Fitch ajax call, you could just do simple
future quizzes with all those then statements and catch all areas in
the catch block. That's perfectly fine. However, sometimes
it can get messy, sometimes it gets confusing. And in those instances where your code starts
getting a bit messy, often, you want to resort
to using async and await. It's just much easier to read. It's much easier to follow. The way I think of it is that
I take an async function. Inside this async function, you can think of it
as being split by 0 or more a weight expressions. And your code within that
function up to and including the first await expression
is run synchronously. We know that
synchronous execution happens automatically by
default in JavaScript. And it's only if and when there is an await expression
inside of their function. Does the browser know to execute this code
asynchronously, aka off of the main thread. It's very, very interesting,
very intuitive. But enough talk, enough theory. Let's hop over to
the next lecture. Let's stop here. And I'll show you an example of using async and using a wait. I can't wait to see, you know.
8. Example of using Async / Await: Actions speak louder than words, which is why, you know,
I love my examples. So let's now use
async and await, and I'll show you how it works. It is very, very interesting. I wanted to find a
function called message. Then I want to execute a whole
lot of things inside here. We notice what I want to
do is I want to eventually get the result of hello world. Eventually try and get to that result just text given
to us by the console, but I want to do it by using
two asynchronous functions. Let's split up each word. Let's first deal
with the first word, put it in a variable
called first word. And I want to now use promises. We cannot normally do this, creates a promise, and
of course we know it gives us resolve and reject. We're not really
using the reject property that
anyway, it's there. If we wanted, we can now use
the setTimeout method just to fake an API call. Let's just create
time, a time gap. Of course, within here, I want to resolve the word hello because this is the
first word we want, and I want this
to take 1 second. We can't do this. Because why? That's right? Because we are
implementing a promise. The results will not be available in that
variable first word. So this won't work. In order to make it work. We want to turn this
entire function into an asynchronous function. We do that by using the
async keyword in front. We now know that
this function is going to return us a promise. But again, line four
will still not work. We're going to get an error. You don't believe me. Let me show you.
Let me show you. At the end we want
to console log. I don't know, Let's use
temporary literals. We can say done. And of course here
we've got first word. This is not going to work. It's now execute our
function called message. We not getting the
results we would expect. In fact, let's go
to the browser. There we go. Let's paste
our code that's executed the message function.
There we go. We get undefined. We getting errors here. That's a problem. We don't want this, we just want the simple message, hello. Not going to work because this first word, property variable, it's not available yet
in order to wait until the promise resolves
and they inputted into that first word variable. We use the await keyword. This is how easy it is to
work with async and await. Well, That's the first word. Before I move on, let's just create a second word. First word. Yeah, we can
call it second word. And we know the second word
is fooled. Here we go. So when we console log and done, we can say first word. Of course we can have resolvers, not the fine, of course
results not defined. And I've called it RES. Know what should I change? I can either make this
result or change at arrays, but let's just
make that resolve. There we go. Now of course, when we execute this
message function, everything should go
according to plan. Does co-occur tells us that
we get console logged, done. Hello World. But my dear students, I want you to understand why. Let me just zoom out.
Let me scroll up. This is our entire code block. Let me explain
what happens here. And this is gonna be very
technical, but it's very, very important for you to
understand this example. We awaited to promises. What's going to happen. Well, okay, let's talk about
the code that gets executed. We know that progress
moves through this message function
in three stages. Stage one, the first
line of the body of the function is going to
be executed synchronously. This is the default
behavior of JavaScript. This means we're going
to hit line for, this is the first thing
that's going to be executed. But now, when the parser
hits that await keyword, the browser knows that there
is a painting promise. It needs to wait for
what's going to happen. Well, the result is
that the progress of our message function
is going to be paused and control is going
to be yielded back to the environment that called
the message function. In this case, I'll mix each function is called
on the window scope and nothing else is happening on the main threats and nothing
else is going to happen. But this is what's happening
behind the scenes. Stage to sometime later when the first promise has either
been for fold or rejected. Control is going to move
back into this message. Function, the result
of the first promise, hear the word hello. It's going to be returned
from the await expression. Here. The word hello is assigned to the variable
called first word. That's done. Progress
will then continue. The past is going to now see
the second await keyword. Again, the browser knows that
there is a pending promise it needs to wait
for and progress. And how many such function is now going to be paused again. And control is going to be yielded back to the environment. That cold message. We just repeating
the process here. Last but not least, stage three, sometime later when the second promises either been
fulfilled or rejected, control is going to reenter
this message function. Of course, the result of the
second promise resolution is return from the second
await expression. In our example,
the word world is assigned to a variable that
we defined as second word. But now's the key
difference because now we don't have another
await keyword. Control is going to move
through this message function, eventually hitting a
return expression. Here we're just console logging something to the screen.
Have you got it? Told you this is very advanced. I hope you're understanding, I hope I'm explaining till you enough really is quite intuitive once you
understand how it works. But before I finish
this lecture, let me just pose you
one more question. Remember I said that when debt await keyword is
hit by the parser, I said control is going to be yielded back to the
environment that called, that makes IT function
in the first place. Remember I said that and he has the window environments
and nothing else happens. But what do I mean? What about if it's
not the window object that called this
message function? What about if it was
another function? I know it's getting
a bit complicated, but let me show you what I mean. Let's go down here. That's not execute this function now let's just comment it out. Let's say we have
another function. And this function, Let's just call execute for lack
of a better word. And inside this function, we want to execute
this message function. And we want a console log
am first to the console. Right now I haven't
executed this function, we've just defined
it, but what do you think is going
to happen now, based on what I said
a few moments ago, to illustrate the
street in a cheap copy, these two functions,
browser, console. What's gonna happen off
I execute this function. Let's try it. How awesome
is that we get executed? I am first, first. And only once all those
set timeouts have resolved that we
get the word done, Hello World returned back to us. Or just students,
how awesome is this? What's really cool
with this though, is that you are
understanding what happens behind the scenes. Because when the parser hits
that first await keyword, that's going to yield control away from this message
function to the environment, then call it, and that is
this execute function. And it's going to continue to
execute code synchronously. We know while it's paused and while that
promises resolving, we know that that console log I'm first going to be given to us first before the entire
message function has executed. The reason I had to go to the browser by the
way, of course, if I execute this function now, why is it not showing anything? Coca-cola and show us the
order in what things are done. So we can see here that we get, I'm first n, we get done. Hello world. We can't see the
order of when it happened. That's why I wanted to show
you here how it works. Let me show you again,
you can actually see the time it takes to execute
those timeouts as well. It's fascinating. So let's define our
functions. Let's execute it. We get immediately,
I'm first we got to wait two seconds and
then we get that done. Fascinating. I want to stop here. I
want to have a break. In the next lecture,
I'm going to show you another quick example
and named finally, I want us to use
what we've learned. I want us to use the async
and await keyword to improve code that we've previously done on
other examples. I can't wait and I'll see
you in the next lecture. Okay.
9. Second Example of using Async/Await: You know, I love my examples
because I really do think examples drive
the point home. I just want you to get very
used to the concept of wind that await keyword
is hits by the pasa. Progress of the entire execution in JavaScript is thin posed in that function and
control is given to the environment that of course
executed that function. I just want you to get
used to that concept. So why don't we create an async function so we know it's going to
return a promise. We use the function
keyword in JavaScript. Let's just call it foo. This is just mock convention. I don't know why we
use food all the time. It's just a made-up function.
It's just a function name. We could have called
it anything we want. I want to now define
a promise and it's instantiate the promised
constructor function. We know we've got x's to resolve and reject in our
constructor function. Of course, what do we
want to happen here? Just get all the brackets
and all that sorted. We are ready to execute. All I wanna do is I want to implement the setTimeout method. I don't really want
anything to happen other than resolving this promise. And we can resolve
the word hello. How's it? Pretty simple in one hundred,
ten hundred milliseconds. Here we go is all very simple
async function called foo. The next thing I wanted to do, I didn't want to
execute this right now. You know what I'm gonna do? Let's actually just write
this in our state at the F, just easier to see
what's going on. Of course, unless inhibit
capital N for new. There we go. Now I'll text editor at least is telling us that
everything's a K. Syntax is very important
when it comes to coding. Obviously, your computer
just understands 1's and naughts, aka
electrical impulses. It's garbage in, garbage
out effectively, if I make any error, if I don't, if I call this promise promises, the JavaScript engine
is not going to understand what
that is, gonna be. Garbage. So anyway, that's why the new keyword
is very specific. And JavaScripts, I have
to use lowercase mu. That was my error. Anyway, we're still
inside this function foo. We've implemented a promise. The promise is going to
resolve with the word hello in 1 second. Now, this is what I want
to show you right up until this point we haven't
used the weight keyword. What I wanna do is I want to
define a message variable. And let's await this promise. To understand what it
is I'm trying to do. I'm going to wait until
the promise above resolves with the word hello. That's what I'm going to do. And then I'm going
to put it into a variable called message. Interesting. Then of course what I
want to do is I want to alert message to the browser. I want that little
pop-up to come up and I want us to see the word hello. Let's go to the browser. Is clear, everything is
define our function. There we go, we've defined it. Let me zoom in a bit given our conversations
we've been having. Given the example I showed
you in the previous lecture. I want you to think
logically what happens here. Well, firstly,
let's just execute this function so you
can see what happens. We've executed it. Resolve is not defined. Let's clear this. I called it. Let's do raise. Here we go. And let's call the
function again. There we go. And we get the
alert saying hello. That of course happened after 1 second, as we would expect. There we go. This makes sense. But do you understand
the logic now? Let me explain the logic tier. You probably know already, but let me drive the point home. Let's look at our code. The function execution is
going to pull which line? Well, it's going
to pause when it hits that await keyword. It's going to pause
online in ate. We know whichever environment
called this function foo, that pain will continue to be executed in a
synchronous manner. When the promise eventually
returns a result, then control is going to be given back to this foo function. Of course then we execute that alert message, makes sense. This is what I
want to emphasize. Using the word await
literally suspends the function execution and
told the promise settles. It's then going to resume
with the promise result. This doesn't cost
any CPU resources because the JavaScript
engine can do other jobs. In the meantime, it can
execute other functions or the scripts handling
beans, etc, etc. It's very, very powerful. But anyways, I think you've got a high-level understanding enough to start digging
deeper into async and await. Before we end this section, this class, I want you to use what we've learned
in a practical way. In the next lecture,
I want to call up some code we've
looked at previously. And I want you to
try and convert that code or improve their
code by using async and await. I can't wait and
I'll see you soon.
10. Challenge intro - improving our previous class Fetch code: Welcome, welcome, welcome. If you having a lot of fun.
Now, all right, Here we are. This is code from
a few sections, classes, Beck and you know, the drawer we had this Fitch API that made calls to do
different websites. The first feature request was to replace this hitting
with our IP address. Mine is not working
at the moment because I am in Zimbabwe, in Africa. And hey, sometimes we don't
have power. Right now. I've got no power,
no electricity. And that means, of course,
no router and Wi-Fi. So I can't taste this
code right now with you. But what I can do is we
can improve our code, we can refactor it. The second face your quiz, we did the remainder
to our own server, showing an image, click on
the button and we show Ajax. If we go to our code, we can see here at the
bottom of the file, this is our feature quest
to Fitch that imagery. And there are a lot
of themes statements. It's a catch statement. I want you to think about
how we can change this, how we can improve this code
by using async and await, give it a go yourself. Let's stop the lecture here.
And in the next lecture, let me code it up with your conduit and I'll
see you shortly.
11. Challenge solution - fetching our Image using async/await: Did you give it a go? I hope so. I hope so because that's
the most important thing. It doesn't even matter if
you didn't get it right. The most important thing
is that you gave it a go. Let me do this in
a piecemeal manner so you understand
what's happening. You might have thought, Hey, we know that Fetch
returns a promise. We deal with promises so we can deal with async and await. But even before it,
you might think, hey, let's put this into a
variable called response. And we can execute
this fetch function. You know what? Let me just, let me just comment everything
else out here. Let's donkey confused.
You might have thought, okay, let's grab our response. We know that responses over readable stream you
might've felt okay, well, let's try and extract
the data by taking that response and executing
the blob method on it. Because we know we're
dealing with an image. It's binary data, it's not JSON. Then of course, let me actually just copy the next lines
of code below here. You might have been saved. Let's define a
picture URL by using the URL interface and
passing in this data object. Might've tried to do that. Then of course, taking the image source elements and assigning it to
that picture URL. Of course, the final
step is to console log success to the screen. Is this going to work? Well, let's test it out and
let's go to our browser. Of course, now when I click
the button, it's not working. What error messages
that we're getting. We're getting a type
error response. Blob is not a function. Do you understand why? Why are we getting
this type error? Well, if we go back to
our code, just remember, the reason we're
getting this era is that although we know the response object
has the blob method, by the time the browser
gets to the next line of code being online
97 and alkanes, the response object,
that variable. It hasn't yet come back
from the phage coal. Remember that Fitch
call is being made on another
thread aside three, that's being made in
parallel to the main thread. That's why we're
getting an error. Okay, client will want or not, then just add the word
await in front of Fitch and await in front of
the blob method, right? Those are the only two
that return a promise, so we don't need to
wait anywhere else. Will this work? Well, that won't work either. Let's go to the browser,
refresh everything. Tick the button. It's not working. It's
not going to work. Why isn't it going to work? That's right. Because you have to use await
within an a sinc function. Then we just have to expand
our code a little bit more. But you'll see it's
worth it because it becomes very easy to read. Remember, we need
the async keyword and then we need to
define a function. Let's just say it's
called Fitch image and everything resides within
these curly brackets. Here we go, starting
to make sense. Now, we've defined a function. We've put the async keyword day, we're using a weight. We can read it in a
synchronous manner. And of course then
we've actually got to implement or execute
this function, right? Otherwise nothing will happen. There you go. This is how we use
async and await. Is this going to work? What do you think? Let's go to the browser. Click the image. Wow, that is very, very cool, isn't it? Don't get lost in
all the detail. It's very simple mount to read. I won't go through the logic in detail because you already
know how that works. But just remember in
our original code, if you scroll down here, we actually implemented
a few other functions, check status and
convert to blob. Right here. We bypass those things
which is not good. We do want to check
the status and we do want to put our logic elsewhere. If we scroll up, we've got the section called
universal functions. We've defined certain functions. We've defined a function
called check status. But what's interesting about it? That's right. It returns a promise. Interesting. And I'll function converts
to blob also returns a promise because we know the blob method
returns a promise. So why did we improve
this code slightly? I think the first line is fine. Response is what we get
back from our fit coal. Then we only want to deal
with a good response. A response. I don't want to execute
our blob function. What I want to do is
I want to implement our check status function and we pass in our response object. We know this. Once we have that good response, the next tip is to
convert it into a blob. So why don't we call it in a blob data for
lack of a better word. And yes, we can execute our
Convert to blob function. That will take our
good response data. There we go. We literally done
the should work. If we go to the browser, everything, click the image. Reference era, daughter's not defined. What have I done wrong? Data here should be
blogged daughter course. Let's go back to our browser. Click Show Image. How awesome is that?
How awesome is that? I'm very, very happy with this. My dear students,
How cool was this? Now I want us to pause
the lecture here. It will stop the lecture here. I want you to try and do exactly the same thing,
improve the code. But if I scroll
up, I want you to do the same for fetching
the IP address. Here it is, the Fitch coal
to get our IP address. Stop the lecture here, try convert this yourself. And then I'll show you how I
did it in the next lecture.
12. Challenge solution - fetching our IP address using async/await: Did you give it a go?
I hope so. I hope so. And I still don't have Internet here ends and
we've got no power. So I can't taste it, but I
will write it off with you. If it's not correct, please let me know in
the Q&A and I'll fix it, but hopefully logical prevail
and it will make sense. So how do we convert this? How do we fix it? Well, firstly, let's get
rid of this entire block. If we don't need it. It's defined now
an async function. We can use the function
keyword in JavaScript. We can call it Fitch IP because it's exactly
what we're doing inside this code block
here we can perform our actual fit your
question, what's next? What do we do?
Well, I don't know. Let's just say our
rural response. I'm just showing you
we can define it. Anything we want is the
result of this Fitch request. And of course I'm using the
async keyword here because we know that that feature
request returns a promise. What's next? Well, we want to check with it, we have a good response. So let's define a
variable called good response and execute our
check status function, which we pass into it,
our rural response. You can really see this is very, very simple, it's
very intuitive. We know once we
have the response back from that FetchRequest, we know to redouble stream. We know it's Jason because
we making a call to this world time API URL and it tells us that we get
given back JSON data. What we want to do is we want to actually define a
variable called data, which is going to be JSON. Actually it's not, it's gonna
be a JavaScript object, but we know it's
gonna be the result of as having cold
the JSON method. We use the keyword
await once again, if we take out good response, we know it has this JSON method. Now let's JSON method. We know from previous lectures that debt returns us a promise. That's why we have to
use the await keyword. Of course, we can finish
off the same tire example. By grabbing our IP
takes query selector. We can grab our HTML element
that has an ID of IP takes, I think that's what we call it. This is scroll up. These are header IP
takes, Can you see it? Let's go small t. If I p takes, Let's
just do small teeth. This change its inner
HTML property to what we know on this
JavaScript object. Let's give them back to us. It has a property
called Client IP. We've done this before. You know what I'm talking about? This should work. Actually it shouldn't
because we haven't executed a function yet. So of course, outside
of this code block, let's execute this function. Mit students, this should work. Like I mentioned, I
don't have power. So it's not going
to work for us. That's why this hitting
taste has not been replaced. But you get the point. I think that logic will stand if there is
something wrong with it. Please just look
in the comments. Some shorts been resolved
already. But yeah. Yeah. Hope you having fun.
I'd be having fun. There's just one more
thing I want to mention. That is eras. Right now. We're not catching errors here. You know what, let me delete plus now let me keep
the common day. It's fine. But right now if we
go back to our image, coal, we're not
dealing with areas. In the next lecture, let me just quickly
show you how we can use a try and catch block
to deal with errors. I can't wait.
13. Error handling using Try and Catch: The final thing I
want to talk to you about is error handling. I mean, we know we've executing check status
convert to blob. And if we go to these functions
at the top of our code, we do have some error handling. We call it reject method. For example, if the response
okay, property is false. But what happens if
we have other areas? What about if we have areas
not in those code blocks? Well, there's a very
easy solution to this. And that is, we can wrap our entire code block
in a try statement. Very, very useful,
very, very intuitive. So we just move our code
all within this try-block. And what that does is it allows all areas to be caught
by this catch block. Course, we get given back an error object which we
can put into any variable. We putting it into a
variable called Era. And then it will execute
this callback function are medically and of course you
can do whatever you want. This just console log that
air object bet to the user. Okay, So we can
literally just do this, put it in a try
and catch pockets. Very simple. I told you, I told you it's not
going to be difficult. And then you have an error, like an incorrect URL. Go to the browser,
go to the console, and click the image. We get an error. And this is our custom error. Let me just prove it to you. Hello World. We got, Let's go back to the browser. Click the image, and
then we go, Hello world. Oops, this catch block is
actually catching the error. I hope that this is
all making sense. If I had a lot of
fun in this false, we have covered a
ton of information. Taking a step back, I want you to realize that you really have
come a long way. You know what JSON data is, XML data, you know the history of Ajax,
where it came from. You know what a constructor
function is that we used to use the XHR object. And list goes on. Walden, pat yourself
on the back. There, we have it. Very, very simple. This was very quick lecture. I hope you can start
seeing the power of using async and await.