Asynchronous JavaScript in ~10 Minutes - Callbacks, Promises, and Async/Await
Summary
TLDRIn this video, JamesQuick dives into the intricacies of asynchronous JavaScript, a fundamental yet challenging aspect of the language. He breaks down the concept into three main categories: callbacks, promises, and async/await. Starting with the basics of callbacks and their potential pitfalls, such as 'callback hell', he then introduces promises as an improvement over callbacks, demonstrating how they handle success and error cases. Finally, he presents async/await as the preferred method for writing asynchronous code, showcasing its readability and ease of use with examples like reading files and making API requests. The video aims to clarify these concepts, making them accessible for web developers looking to master asynchronous JavaScript.
Takeaways
- 😀 Asynchronous JavaScript is a fundamental concept in JavaScript that makes the language unique and is essential for day-to-day coding.
- 🔄 There are three main categories of asynchronous JavaScript: callbacks, promises, and async/await, each with its own approach to handling asynchronous operations.
- ⏱ Callbacks are functions passed into other functions to be executed later, often used in scenarios like `setTimeout` and event listeners, but can lead to 'callback hell' with nested functions.
- 📚 Error-first callbacks are a pattern where the first parameter of a callback function is reserved for an error object, allowing error handling within asynchronous operations.
- 🔄 Promises are an improvement over callbacks, providing a more manageable way to handle asynchronous operations with `.then()` for success and `.catch()` for errors.
- 🔄 `fs.promises` in Node.js and the Fetch API are examples of built-in modules that use promises to simplify file operations and HTTP requests respectively.
- 🆕 Async/await is a newer feature that simplifies writing asynchronous code by allowing the use of `await` to wait for a promise's resolution within an `async` function.
- 👍 Async/await is the preferred method for the script's author due to its readability and ease of handling errors with try/catch blocks.
- 🛑 Unhandled promise rejections can occur if the error case is not properly caught, highlighting the importance of comprehensive error handling in asynchronous code.
- 📚 The script provides practical examples of asynchronous JavaScript, including reading files, handling HTTP requests with the Fetch API, and dealing with errors.
- 🔧 Converting older callback-based code to promises and then to async/await is a way to modernize and improve the structure and readability of JavaScript code.
Q & A
What are the three main categories of asynchronous JavaScript discussed in the video?
-The three main categories of asynchronous JavaScript discussed in the video are callbacks, promises, and async/await.
Why is asynchronous JavaScript considered an important concept to learn?
-Asynchronous JavaScript is important because it is core to how JavaScript works, especially in day-to-day coding, and it makes JavaScript unique compared to other languages.
What is a callback and how is it used in JavaScript?
-A callback is a function passed into another function to be executed later. In JavaScript, callbacks are used in scenarios like setTimeout, where the callback function is executed after a specified delay.
Can you explain the concept of 'callback hell' mentioned in the video?
-Callback hell refers to the situation where multiple callbacks are nested within each other, leading to complex and hard-to-maintain code structures that resemble a 'Christmas tree' pattern.
How does the video demonstrate the use of callbacks with events in JavaScript?
-The video demonstrates the use of callbacks with events by showing an example of using `button.addEventListener` to listen for a click event and execute a callback function when the event occurs.
What is an 'error-first callback' and why is it significant?
-An 'error-first callback' is a callback pattern where the first parameter is reserved for an error object. It is significant because it allows developers to handle errors in asynchronous operations more effectively.
How does the video explain the evolution from callbacks to promises?
-The video explains that promises evolved from callbacks to provide a cleaner and more manageable way to handle asynchronous operations. Promises use the `resolve` and `reject` functions to handle success and failure paths, respectively.
What is the main advantage of using promises over callbacks in JavaScript?
-The main advantage of using promises over callbacks is that promises allow for better error handling with `.catch()` and make the code more readable and maintainable by avoiding deeply nested callback structures.
How does the 'async/await' syntax simplify writing asynchronous code in JavaScript?
-The 'async/await' syntax simplifies asynchronous code by allowing developers to write code that looks and behaves more like synchronous code. It uses the `await` keyword to pause the execution of an async function until the promise is resolved or rejected.
What is the purpose of the 'try/catch' block when using async/await?
-The 'try/catch' block is used with async/await to handle any errors that occur during the execution of the asynchronous operations. It allows for error handling similar to synchronous code.
Can you provide an example of how the video uses async/await with the fetch API?
-The video demonstrates using async/await with the fetch API by defining an async function that awaits the fetch request, awaits the JSON response, and then processes the data. If an error occurs, it is caught and handled in a try/catch block.
Outlines
😖 Understanding Callbacks in Asynchronous JavaScript
Jamesquick introduces the complexities of asynchronous JavaScript, focusing on callbacks as the first category. He explains that callbacks can lead to 'callback hell' due to nested functions, which can complicate code structure. He also discusses the importance of error handling in callbacks, using 'fs.readFile' as an example to demonstrate error-first callbacks, where the first parameter in the callback function is reserved for error reporting.
🚀 Promises: The Evolution from Callbacks
The script moves on to promises, which are presented as an advancement over callbacks. Promises are objects representing the eventual completion or failure of an asynchronous operation. The video explains how to create and use promises, including the use of 'resolve' and 'reject' to handle outcomes. It also covers the use of '.then' for successful outcomes and '.catch' for errors, providing examples with 'fs.promises.readFile' and the fetch API, illustrating a cleaner and more manageable way to handle asynchronous operations compared to callbacks.
🔥 Embracing Async/Await for Cleaner Async Code
The final part of the script introduces async/await, which is portrayed as the preferred method for writing asynchronous JavaScript by the presenter. Async/await simplifies the code by allowing the use of 'await' within an 'async' function to pause the execution until the promise is resolved, after which the subsequent code can use the result directly. The video demonstrates how to use async/await with 'fs.promises.readFile' and the fetch API, also highlighting the use of try/catch blocks for error handling. This method is praised for its readability and is the presenter's recommended approach for modern JavaScript development.
Mindmap
Keywords
💡Asynchronous JavaScript
💡Callbacks
💡Promises
💡Async/Await
💡Error-first Callback
💡Node.js
💡Fetch API
💡Unhandled Promise Rejection
💡Try/Catch
💡JSON
💡Event Listener
Highlights
Introduction to the concept of asynchronous JavaScript and its importance in web development.
Explanation of JavaScript's asynchronous nature and its uniqueness compared to other programming languages.
Overview of the three main categories of asynchronous JavaScript: callbacks, promises, and async/await.
Introduction to the callback concept with an example of using setTimeout.
Demonstration of 'callback hell' with nested setTimeout functions.
Example of event listeners as a common use of callbacks in JavaScript.
Introduction to error-first callbacks and handling errors in asynchronous operations.
Explanation of promises as an evolution from callbacks, with resolve and reject mechanisms.
Demonstration of creating and using promises with fs module for file operations.
Introduction to the fetch API and its use with promises for making HTTP requests.
Explanation of async/await as the latest feature for writing asynchronous JavaScript.
Conversion of callback-based code to promises for better error handling and readability.
Use of async/await for simplified error handling with try/catch blocks.
Application of async/await in fetching data from the Pokemon API.
Personal preference for async/await over callbacks and promises for readability and ease of use.
Invitation for viewers to share their preferred method of handling asynchronous JavaScript.
Conclusion and anticipation for the next video on web development topics.
Transcripts
asynchronous javascript callbacks
promises async await huh this was one of
the most difficult concepts for me to
learn in javascript but don't worry
because we'll break it all down in about
10 minutes all right first off if you're
new to the channel welcome my name is
jamesquick
and every week i do one to two and
sometimes three videos on web
development
including topics like asynchronous
javascript which i am really excited
about because
asynchronous javascript learning how how
and why javascript is asynchronous and
how to work with it
is one of the most important concepts
you can learn in javascript specifically
it makes javascript as a language a
little bit more unique in comparison to
other languages
and it really is just core to how
javascript works and the javascript
that you will be writing in your
day-to-day so there's three different
categories
commonly of asynchronous javascript
we'll start off with callbacks we'll
talk about those
then we'll get into promises and we'll
talk about those
and then we'll talk about async await
which is a newer feature in javascript
that really
kind of streamlines the process of
writing asynchronous code and is my
personal preferred way to write
asynchronous javascript
so make sure you stick around to the end
to know how to write javascript
asynchronous javascript in the latest
and greatest
and my favorite way so let's go ahead
and get started and i've got lots of
different callouts in here for different
things we're going to do
let's start with the idea of a callback
and an example of this is one we've
probably seen
many times it's where we can do a set
timeout for example
and a set timeout will take a callback
function and you've probably heard that
term in that sense before
and in this case what we're saying is
we're calling timeout we're passing it
this function which will log out
waited for one second and we're telling
it how long to wait before it does that
which is in this case
one second which is a thousand
milliseconds so we save this and after
about a second we should see that
message come up
now this is asynchronous because we tell
it hey in the future javascript lan
node call this function after the
appropriate amount of time that's why
that is java or that's why that is
asynchronous it's also javascript
so i want to give you a little bit
deeper of an example here where you can
have
nested set timeouts and this gets uh
into an example of
demonstrating the callback hell that you
can get into and you get into this kind
of like christmas tree pattern but
you have a callback function here and
that thing is waiting a second and then
logging out three and then inside of
that you call a function that then takes
a callback function inside of that one
you then have a callback function
so this is callback hell where you're
nesting and nesting and nesting this
stuff and this will do maybe what you
expect where it'll do wait a second then
do three
two one and then you're on so those are
your traditional callbacks are a
traditional
kind of simple examples you could also
have something like this where if let's
say we had a button
in browser javascript and we called
button.addeventlistener
and we listened for the click event and
then passed it
a callback function and this is another
example of a callback where we register
for this event and then our handler the
callback here
is this part here now this code is
running in node so i don't have access
to the dom and dom
element so i'll get rid of this just
wanted to show you that that's another
example
a common example of callbacks in
javascript let me comment this one out
so now let's talk about the idea of an
error first callback this is where
all the code that we've run so far in
those callbacks there's not really much
of a chance for anything to go wrong but
what if it does
so let's do an fs.read file
and i've imported the fs module up here
as well as
a node fetch we'll talk about that in a
minute and the fs module is the file
system module
inside of node so in this case we're
wanting to read a file
so let's do an fs read file
we'll tell it which file we want to read
we'll tell it what kind of
encoding we want to convert it to which
in this case is utf-8
and then we'll have a callback that
takes two properties
an error property as the first one or
parameters error as the first one and
then data as the second one
and the reason is you might fail to
actually read this file so if we just
start with logging out
data and it's done correctly you can see
it has the text here from
that text file and hey this is an
awesome video that's cool
but what if something goes wrong what if
we type in test.2 well it's saying
undefined here because there is no data
because an error happened
so a traditional way that you'll see a
lot of this code is something
like this and i'll just kind of paste in
this example where you first
check for an error so if there is an
error property log that out and then do
whatever you want otherwise you can
assume the data is good
so in this case it logs out the data and
then if we uh through an
error here it will handle that thing and
then log it out with this log here
and again it's throwing an error because
this is a file that doesn't exist
all right so that's the idea of an error
first callback and that's really
important when we get into promises and
async await is these things that are
asynchronous
sometimes things go wrong and we need to
be prepared to handle those errors
all right now let's talk about promises
which is kind of like the evolution of
the idea of callbacks and i want to
start by creating a promise
so by creating a promise you're passing
it a function
that accepts both a resolve and a reject
callback basically and then in your code
you want to detect whether or not this
thing is successful or it failed and
then if it's successful you call resolve
if it rejects if it fails you call
reject and so i'm going to take a little
bit of snippet here to get a random
number that is either a zero or a one
and then i'll say if the random number
is
zero i'm going to consider that to be a
good
thing so i'll call resolve else i'll
call
reject so again promises always have a
success path and a fail path
referred to in this case as resolve and
reject and then we'll see what that
becomes when we use
a promise in a second so since we have
this promise we can call the dot
then and dot then will take
a callback function where we can log
something like
success and we'll save this and we'll
refresh and we start by saying that
there was an unhandled promise rejection
so let's save again
then we see success and success and
unhandled promise exception
the reason is that when we use this
promise remember it can resolve or
reject
the the dot then in this case passing
this handler
to the dot then is only handling the
success case
if we want to handle the bad case the
error case it's a dot
catch and then we can do a callback
function here
with a console error of something
went wrong all right so now we say this
say this you see something went wrong
and then something went wrong and then
success so we're handling both of those
so we create a promise with a function
that takes in resolve and reject
and then based on the action that goes
inside of this function
you or the promise itself will decide
whether or not that's actually
successful or not
all right so that is us creating a
promise but what if we just wanted to
use
an existing promise well we can use in
the fs modules there is a promises
set of functions where we can call read
file
in the same way we just did all right so
this would be doing fs.promises and then
calling read file the exact same way
that we just did
and now instead of using callbacks we
can handle the dot then
and the dot catch and you'll notice uh
often you see
uh these returned on a new line for
readability and that's a really good
habit to get into
so if this success successful we'll get
the data back and we can log that out or
there
is a dot catch for an error
and then we can air that out all right
so there's our text if it passes and
then if it fails if we did a test.2
now you see that this thing is handling
the error so this little snippet up here
is how we do
read files with promises versus
this one up here and you can tell that
this is a little less code that we're
having to write with promises so this is
kind of an upgrade here
now another good example of promises is
with the fetch api
and fetch api is how we make xhr
requests to a server
and a good fun example of that that i
like is using the pokemon api
so you can call the pokemon api and you
can get some information about a pokemon
back
so if we want to use that inside of node
there's a node
fetch package that i have installed so
that we can do fetch the same way we
would inside of browser javascript
so we'll paste in that url and then just
like what we just saw we can actually
copy this you can see that that promises
will
follow a pretty similar format well
we'll have
a success case which is in the dot then
and then we'll have the uh not success
case which is in the
catch so you can see this is successful
it gives us back lots of information
about our response but it's not quite
actually the data that we're looking for
so actually what happens is this gives
us back a response
and then what we want to do is get the
json out of that response
and getting the json out of that
response happens to return a promise
which means we can then chain on another
thing here
where we're going to get the actual data
so then we'll log out
the data and we should see that that
comes back with
abilities and name and url so let's take
a second to break this down again
we call fetch we handle the success case
with dot then
we get the response which is just the
raw response that comes back and then we
need to convert that thing to json
so res.json returns a promise then we
can
chain on a promise dot then to handle
that promise
and then we get the actual data and we
log it if this
were to be bad it would trigger
our catch so you can see if we typed in
something like undefined
you can see that that is going to throw
an error it says invalid json but we're
able to handle that
inside of our catch all right so now i
want to show you
the evolution of promises to async await
this is my favorite way to write
asynchronous javascript this is the way
that i
always do this so i'm going to copy in a
snippet here this is going to be an
updated snippet
of our load file work that we've done in
the past
all right so this is going to be an
updated snippet of the read
file so this is going to be an updated
snippet of the read file stuff that
we've done a few times now
all right so now in this case what we're
doing is we're defining a load file
function and the reason is if we want to
use
this async await capability we have to
mark a function as async so this is
looks like a regular arrow function
except we add the async keyword
so now this is an asynchronous function
which means inside of this
we can use the await keyword so what
will happen
is we'll call our fs promises read file
the same way we did before
but instead of passing callbacks or
doing a dot then to handle the responses
we add the await keyword and we get our
data right here that's really cool this
is much more streamlined and a lot more
readable for me especially or this is
my preference in terms of readability so
now if we save this
uh we'll get this is an awesome video so
we see that response coming back again
so all that is working
but the problem is what if we do an
error here what if we do test.2
well that actually throws an error and
that's where we take this one step
further
where we have a try catch and so what a
try catch is saying
it's like hey let's go ahead and try to
run some code which will be this code
here
if some sort of error happens now we can
handle
that error inside of this catch this way
so we'll log this thing out in this case
what this should do is it should safely
handle this response
log out the air but we're still able to
use our async await functionality
again i love async await this is code
that i write all the time
inside of my personal javascript code
all right so let's take this uh one
last up further and i'm gonna copy in
the fetch pokemon
example so here's our new fetch pokemon
function and it will make a fetch
request the same way we saw before
except it's awaiting that response
getting the response here
and then it's awaiting the res.json
remember that this res.json returned a
promise before
so now we can await that response the
same way we do the original fetch
request so we make the request we await
the response
we take the response we convert it to
json and we await that
and then we end up getting our data so
in this case i'm passing in an id of a
pokemon and then making that request we
should see that we get information
coming back but
what if we pass in nothing which would
then make this id undefined
and throw an error we're not handling it
and you'll see that we get an unhandled
promise exception here
which means that we need to go and
handle this with our try catch so the
same way we did this before
here's our try this is the code that we
want to try and then we'll catch an
error and then error that
error out if there is one so now you can
see that it throws that or it
logs out or errors out that error
appropriately
just like we did with our read file but
now this is the type
of asynchronous javascript that i prefer
to use i love using async await myself
i use async weight in every instance
that i can i
almost never use callbacks if i can
avoid it and there are some things that
you can do
to kind of convert older callbacks to
promises
so you can look that up or if you're
interested in knowing how to do that let
me know in the comments but i will
always use
async await in my javascript i'm curious
if you've seen
these different formats for doing
asynchronous javascript what is your
favorite callbacks promises
async await let me know in the comments
which one of those you prefer
hopefully you enjoyed a lot in this
video about a cool
challenging topic in asynchronous
javascript and i'll see you in the next
video
浏览更多相关视频
Asynchrony: Under the Hood - Shelley Vohr - JSConf EU
Javascript Promises vs Async Await EXPLAINED (in 5 minutes)
What the heck is the event loop anyway? | Philip Roberts | JSConf EU
Top 9 JavaScript topics to know before learning React JS in 2024
How to use escaping closures in Swift | Continued Learning #20
RxJS Top Ten - Code This, Not That
5.0 / 5 (0 votes)