Transcripts
1. INTRODUCTION: Welcome to the asynchronous
JavaScript class. In this class, we are
going to learn callbacks, promises, and async await, which are the most
important topics for JavaScript developers, especially those who want
to master, react or node. If these concepts are cleared, then you can easily learn other concepts in
React and node. Yes, you will get
all resources for the exercise and the digit of these concepts in
projects section. So let's don't waste
time and get started.
2. Synchronous vs Asynchronous: So first of all, let's
understand the difference between synchronous
and asynchronous. So here I create
index.html file. And in this JavaScript folder, we have script.js file. And I linked this JavaScript
file with our HTML file. Now let's copy this
HTML file path and paste it in browser. And let's open console rate. Now in this JavaScript file, I write console.log first line. After that, another
console.log last line. So this is the example of synchronous code
or blocking code. Because when this
first line is execute, the code is blocking. And this last line has to wait until this first line
finish the task. In other hand, beheld asynchronous or
non-blocking program. Let me show you the example
of asynchronous code. In JavaScript. We have one function
called setTimeout. Now the first
argument is function, and the second argument
is time for delay. Let's say 2 thousand
milliseconds, which is two seconds. After two seconds, this
function will run. So imagine here we are
getting data from database, which takes two seconds. Now, can you guess what
we get in console? Let's see. So I refresh the page and see we get first-line and last line. And after two seconds, we get this getting
data from database. So first of all, this
first line will execute. Then we call this
setTimeout function. This function will schedule
a task, perform in future. This doesn't block the goal, and that's why we call it as non-blocking or
asynchronous code. So when we run this code, we get this first line, then immediately last line. And then after two seconds, we get this line. Let's understand this with
the real life example. Here is a one restaurant. The waiter come to Table one
and take order from them. Now waiter give this order to kitchen and then move to
table 2 or another order. So there's one rater can
serve more customers. So this is the example
of asynchronous. Now that is a another
restaurant ray diagram to table one and take
order from them. Now waiter give this
order to kitchen and then waiting for
the code to be ready. He's not taking order
from another table. So the restaurants system is going to block because of this. And this is the example of
blogging or synchronous score. So synchronous or asynchronous
is the type of code. Now here, let's make this
example more realistic. So I create a
function called get student and move this
timeout function inside. This function will return here data of student object name, bob, an ID to one. Now, let's call this
function here and store this value in a
variable called student. And after that, we
simply log the student, Sylvia, assuming that we are
getting data from database. And it takes two seconds, save this and refresh the page. See, we get this student as undefined because this function is executing after two seconds. So when we call this function, this written data
is not available. If we want to return a
value from this function, then you have the right
return statement here. But that's not we want because we are getting
data from database. And it can take once again, those second or more than that. So that's why we use setTimeout to add
delay in this task. Now, how can we get
this student data here? So there are three methods
to handle asynchronous code. Callbacks, promises,
and async await. So let's start with callbacks.
3. Callbacks: What is called a callback is a function which is executed. I've done another function
finished execution. In other words, any
function that we pass as an argument
to another function. So we call that
function as a callback. Let me show you.
So I just add here id parameter and
buys this id here. In function, we pass one, which I forgot to add. So to apply callback, we have to make little
gene's function definition. So I add here
argument called back. Now these callback is function. So we call this function
while printing data. So after this console, we add callback and Gaul. This function here now buys the student data
in this call back. And let's remove this return. We don't need it anymore. Now we are not returning anything from this
GetString function. So we no longer need to store this function value in variable. Now for our second argument, we have to pass
function I use here at a function and move these
console in this function. Now, let's get the student
details as student parameter. Now you might think
this is confusing, but trust me, this is not. Let me explain you from Start. Here. We are calling this
sketch to run function, and we pass this one as IID. So after two seconds, beget console this line. And after that, this
callback function will run, which we pass a second argument. So we get this object data
in this two random variable. And then we can solve this
student data simple as that. So save this and
refresh in browser. See, we get this first
line, last line. And then after two seconds, we get this line. By using this technique. We don't get undefined
data as we got previously. This callback function will
run after two seconds. Now the funny part
is you already use callbacks in your code
before this tutorial. So pay attention on the syntax
of setTimeout function. The best argument is function, and second argument is time. So we know that when we pass function as a parameter
in another function, then we call this
function as callback. Now, imagine here we want to get another data
from the student, let's say subject
information of the student. So I create another
function called gets objects and bias here, id, which is student ID. Now inside this function, we are assuming that the aggregating data
again from database. So I add here setTimeout and Baz function
as first argument. And two seconds. Now here, first I console
getting subject of student and pass here this ID. And I didn't subjects like
math, science, computer, etc. Now, let's call this
function here and pass ID, which is student dot ID. But as we know, we don't get data immediately. So we use callback. So here we add callback. And before written, we call that callback function and pass this array
in this callback. And remote is written. Now let's define the
callback here and get these subjects that are
in the subjects variable. And after that, we can
console the subjects, save this, and refresh the page. See, what should we get? Post line, last line. Then after two seconds, we get student data, and after another two seconds
we get subjects data.
4. Solving Callback Hell: Now there are some
problems with callbacks. Let me explain you. Here. Let's say we want to get
marks of these subjects. So I quickly create
one function called GetMax and pass object as
parameter and call back. Now I just copy this
setTimeout function and paste it here. Let's change the
console message, which is getting marks off. And bias here
subject and bias max in this callback, let's say 80. Now we call GetMax and
we pass here subject at 0 index and then redefine our callback
for print. This marks. So write console.log mark. You see there is a
nested structure because we are calling multiple
callback in one callback. And this will make our code hard to maintain and understand. This issue is known
as Callback ****. This is not, we have
an asynchronous score. So if these all function
are synchronous, our code look like this. You can see how these
synchronous code is easy to understand
and maintain. So to solve this
callback **** problem, we will make anonymous
function to name function. In other words, as we declared
here, callback function, which is anonymous function
because it's don't have name and define them separately
as named the function. So we define here function called display max and we
get Mark as parameter. Simply console this mark display malloc function
is same as this callback. So let's replace it
with our function. Now here we define a function
called display subjects. And we get subjects as parameter here and copy these
two lines from here, and paste it inside our
display subjects function. So this function is
same as this callback. We can replace it with
displays subjects. Now same for this callback. We create new function
called display student and get students
data as parameter. And then we simply copy
this and paste it here. Now, we can replace this callback with this
displaced student. Note that we are not
calling this function. We just pass reference here and see we don't have
that nested structure. So I copy this code in new
file called callbacks ab.js. So you can refer to this
score in the future. Now this approach is not ideal, but it is better
than Callback ****. So that is a better
way to deal with asynchronous code
by using promises.
5. Implement Promises: So what is promise? A promise is an object
which is able to hold the result of an
asynchronous operation. In other words, Rami's is
promised you to give you the result of the
asynchronous operation or give you error. Let me explain you
with an example. Here. I create new file
called Promises ab.js and link that with
our index.html file. Now to create promise, rewrite new keyword,
and then promise. Now this promise function takes an argument which is function
with two parameters. Here. First parameter is resolved and second parameter
is rejected. And arrow function. Inside this, we write
our asynchronous score. Here. Again, we are assuming that we are getting
data from database. So we write here setTimeout and bars function
and two seconds. Now, imagine here we get
our data from database. So I create one variable called
student equals to object, let's say id2, one name to Bob. Now we write here
resolved because we successfully get data and we pass here the
student variable. Now let's do this promise
in variable called promise. And let's consume this promise. I promise, which is
the variable dot. Here. We have two main
methods then and get. So when we create promise, it is in pending state. And if we complete the
asynchronous tasks, then Brahmins in
fulfilled state. And if that is an error, then Brom is in rejected state. Here, our promise fulfilled because we call here resolved. So when promise is fulfilled, then we get our data
in this band method. Now we store our data in result parameter and then simply
console this result. Save this, and see
after two seconds, we get this result. Now imagine for some reason, we don't get data from database. So I comment out these lines and call here reject function. Now for better practice, every time we create new error and bias our
error message here. Save the changes and
repress the page. See, we get this error here. Now, let's see how to
consume these error. So after this 10-meter, we add another
method called catch. And we get adder and
console.log this error, this NC, we get that error here. So this is the implementation
of promise in JavaScript. Now, let me show you
how we can convert our previous code in promises. So I have this code, whichever Callback **** problem. So let's start with this
get student function. In this function, we
return new promise AND function with resolve and reject variables inside
this error function. Remove this code. Now, let's remove this callback. We don't need it and add
the place of this callback. We add resolved. Now let's test this promise. Here. We call this sketch run
function and pass id1. Now this gets swollen function
will return the promise. We store this promise
in variable called promise than we consume this promise and add
here than method. Now we get this data in student parameter and simply
console.log the student. Now let's comment out this code. And I link this script
file with HTML file. Save this and refresh the page. See, after two
seconds, we get data.
6. Exercise & Solution: Now, if you follow
along with me, then I have one task for you. I want you to convert this
both functions into promises. So pause this video here
and try it by yourself. And after that, watch the
solution. In this function. We return and just write here New and select this new promise. See, we get this boilerplate
by using this small tricks, you can boost your productivity. Now, move this code
inside this function and remove this callback and
replace this with the result. Now here, we also create a new promise and move this code inside
this arrow function. Now remove this callback and replace this
with the result. We convert our old
function in promise. Now, let's see how to consume
this nested promises. So we remove this console from here and call our next function. We just get subjects and
pass year student dot id. Now we know that this function
will again return promise. So we have to use then method. Outside of this 10-meter, we add another than
stored in subjects. Now after that, we call GetMax function and pass
here our first subject. Now we get another promise here. So we add one more than
matter and store this mark. And simply console
dot log this mark, save this and refresh the page. See it's running same as before. Now we can see when
we use callbacks, our code looks like
this nested structure. And after we apply promises, the same goal looks like
simple and in line. Now for good practice, we always add cash method, header and console.log error. So if we get an error in any of these promises than the single
catch function will run. Simple as that. Now we can even simplify these promises
using async await.
7. Async Await - [Best way to Handle Promises]: So async await help us to write asynchronous code like
synchronous core. It's like a magic. Let me show you here. I call this function
get student with id1. Now, when we calling
any function which is returning a promise, then we can wait for that
result and then store that result in variable like we did it in
synchronous code. So let's store this in a
variable called student. Now similarly, we call
the next function, which is get subjects and
Bhatia student dot ID. Now let's wait for that and stored in a variable
called subjects. Now after that, we call
our last function, which is GetMax and bias fascia object from
the students array. Now let's also a weight for that and store this
in Mark variable. And then we
console.log this mark. Now you can see by using this
async and our interpreter, we can write asynchronous code, looks like synchronous core. This is easy to understand and maintain in compared
to callback, as well as promises. We don't need to write this
ten meter again and again. Now you might have aggression. That is async. So whenever we use
await operator, we have to move that in
function with async operator. Let me show you. So I simply add
function here called display data and move
this code inside it. Now at the beginning of
this function, I add async. That's it. Remember, without this acing, you can't use of
eight in your code. It will give you error and edit, and let's call this
display data function. Now I comment out
this promises part. Save this and refresh the page. See, we get the same
desert with async await. Our code looks like synchronous,
but under the hood, JavaScript engine convert
discord in something like this, cool or cold, work like asynchronous core and looks
like synchronous code. Simple as that. Now in promises, we handled error using
this get method. But how can we handle
that error in this async and await approach
for error handling. We use try and catch block. So I write here dry. And inside this try block, we move our old code. And after that, we
add catch block. And this catch block
gets error object. And we simply console
dot log this error. So in simple terms, if any error occurred
in this try block, then this guy's blog will run. So I comment out
this mark variable, part tasting, save this
and refresh the page. And see we get this error. Mark is not defined. So when we use async
await as a good practice, we always break up our code
and try and catch block.
8. Recap all concepts: Let's recap what we learned. So callback function is the best method to handle
asynchronous score. But in callback function rupees The issue called callback ****. Now after that, we see promises, which simply promised
to give you the result of asynchronous operation
or give you error. So to create promise, we use new promise and inside it we pass function
with two methods. Result, reject, the sole means fulfilled and
reject means rejected. But with promises, we also
get this nested and methods. So after that, we see
async await operators. This async await is work like asynchronous code and looks
like synchronous core. So when we call the function, we add a weight operator
at the beginning. This will help us to write
code in synchronous way. And most important,
you have to put this code into a function
with a single operator. Without async, await
will not work. And that's why it
known as async await. And last thing, error handling. We use try and gauge block, gasp for errors, and
dry for all code. So we place our old code in try block and we handle
error in catch block. So congratulations, you've
completed this class, and I hope you
understand these topics. If you liked this class, you can share your reviews. It will help me to reach
more students like you. So see you in the
next class. Goodbye.