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
You learn that when working with promises
it's best to call catch on a rejected
0:00
promise, if you don't
the promise might silently fail.
0:02
Behind the async await syntax
we're working with promises so
0:05
it is possible to call catch even then or
finally on an awaited promise.
0:09
For example,
in the getPeopleInSpace function I'll
0:13
chain a catch method to the first
fetch method that logs the message,
0:16
error fetching data,
along with the rejection reason.
0:21
This will catch a rejected promise
returned by this fetch call, for example.
0:28
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