Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Well done!
You have completed Asynchronous Programming with JavaScript!
You have completed Asynchronous Programming with JavaScript!
Preview
Since you're working with what looks like synchronous code, async functions can use try...catch
to handle any errors. try...catch
is the most common way to handle exceptions when using async/await.
Resources
- try...catch – MDN
- return await promiseValue vs. return promiseValue
- throw – MDN
- console.error() – MDN
Using try...catch
and async/await in the event listener
btn.addEventListener('click', async (event) => {
event.target.textContent = 'Loading...';
try {
const astros = await getPeopleInSpace(astrosUrl);
generateHTML(astros);
} catch(e) {
peopleList.innerHTML = '<h3>Something went wrong!</h3>';
console.error(e);
} finally {
event.target.remove();
}
});
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
Currently our async await function and
0:00
promise sequence do not handle
exceptions and rejected promises.
0:02
You learn that when working with promises
it's best to call catch on a rejected
0:07
promise, if you don't
the promise might silently fail.
0:11
Behind the async await syntax
we're working with promises so
0:14
it is possible to call catch even then or
finally on an awaited promise.
0:18
For example,
in the getPeopleInSpace function I'll
0:22
chain a catch method to the first
fetch method that logs the message,
0:25
error fetching data,
along with the rejection reason.
0:30
This will catch a rejected promise
returned by this fetch call, for example.
0:37
And I could do the same with
the next fetch method, but
0:47
now we're seeing our function starting
to get a bit messy and harder to read.
0:51
So I'll delete these two catch methods.
0:57
And instead I'm going to catch all
exceptions in one place by writing
0:59
a separate async function that handles
the fetching and parsing of data.
1:04
And since we're working with what looks
like regular synchronous code the function
1:09
will use a try catch statement
to handle any errors.
1:13
Try catch is the most common way to
handle exceptions when using async await.
1:16
I'll name the function getJSON and it will
take the URL to fetch as its argument.
1:22
This is an asynchronous function so
I'll tag it with async.
1:29
Try catch consists of two main blocks,
try and catch.
1:33
Try will contain all the code
that needs to be executed and
1:38
any code inside catch will be executed if
an exception is thrown in the try block.
1:42
When an error occurs catch gets
an error object containing the details
1:48
about the error.
1:52
So let's have error
represent the error object.
1:54
Next, inside the try block I'll add
the data fetching statements like earlier.
1:58
Initialize a variable
named response whose value
2:02
awaits the promise returned
by fetch passing it
2:08
url then I'll return await response.json.
2:13
Returning await response.json
means that the function is
2:18
going to wait for
response.json to resolve or reject.
2:23
If it rejects it's going to throw
before returning anything and
2:27
any errors thrown will be
caught by the catch clause.
2:31
Next, if an error occurs when fetching
data from any of our endpoints or
2:35
when parsing the data we'll
handle the error inside catch.
2:39
In the catch block I'll use a throw
statement to rethrow an exception after
2:43
it's caught by catch using the throw
keyword followed by the exception or
2:48
error object.
2:53
The benefit of doing this is that any
errors caught here will bubble up and
2:54
be caught by try catch blocks or
catch methods at the top level.
2:59
For example, a catch method in the click
event listener, which we'll add shortly.
3:03
Next, in the getPeopleInSpace function
we're no longer going to call fetch.
3:08
Instead we'll call
the get JSON function so
3:13
we can delete the variable
peopleResponse and
3:16
set the value of peopleJSON to a await
getJSON passing it the url to fetch.
3:20
Remember, getJSON is an async
function that returns a promise so
3:26
we still need to await that
promise with the await keyword.
3:30
In the map callback I'll
also delete the fetch
3:34
statement stored in profileResponse and
3:39
set profileJSON to await getJSON
passing it wikiUrl + person.name.
3:43
All right, let's test our code.
3:50
So far,
everything works as expected, good.
3:54
Finally, to handle any other errors
which may occur in our async code and
4:01
display a user friendly message I'll once
again chain a catch method on the promise
4:05
returned by getPeopleInSpace
just above the finally method.
4:10
Here I'll set the innerHTML of
the page's peopleList container div.
4:18
To an h3 that displays the text,
something went wrong and
4:26
log the rejection reason to the console.
4:32
This time I'll use console.error so
4:36
that the information is formatted
as an error message in the console.
4:38
Again, this also means that any
exceptions caught up here in the getJSON
4:44
function's try catch will bubble up and
be caught here in this catch method.
4:50
So now any time getPeopleInSpace
rejects a promise,
4:55
if there's an issue with one
of the endpoints, for example,
4:59
users will see the message,
Something went wrong in the browser.
5:02
And in the console we also get
the rejection reason TypeError: Failed to
5:06
fetch as an error message.
5:11
All right, our project app
is now complete, nice work.
5:14
To learn how to write the code inside
the event listener using try catch and
5:18
async await check out the code snippet
in the Teacher's Notes with this video.
5:23
Hopefully, this course helped demystify
some of the concepts of asynchronous
5:28
programming in JavaScript and
5:32
gave you a better understanding of working
with callbacks, promises, and async await.
5:33
So that you can confidently and
appropriately apply them in your projects.
5:37
I encourage you to experiment with each of
the methods you learn, especially the more
5:41
modern and elegant tools like promises,
fetch, and async await.
5:45
To get started practicing
what you learned,
5:49
why don't you try converting callback
based code to promises or async await.
5:51
Or maybe you have a project that
uses XHR to make AJAX requests,
5:55
try implementing fetch API instead.
5:59
If you have questions about
anything covered in this course,
6:01
feel free to reach out to the Treehouse
staff or other students in the community.
6:04
Thanks everyone and happy coding.
6:07
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up