Handling errors when awaiting an async function
So far in this chapter, we've seen how to work with async functions that fulfill successfully. But, as we know, this is not always the case. We need to be able to handle errors that are thrown by asynchronous functions, or any functions they call.
In this recipe, we'll see how try-catch blocks can handle errors that are thrown by async functions.
Getting ready
This recipe assumes you already have a workspace that allows you to create and run ES modules in your browser. If you don't, please see the first two chapters.
How to do it...
- Open your command-line application and navigate to your workspace.
- Create a new folder named
4-07- async-errors-try-catch. - Copy or create an
index.htmlthat loads and runs amainfunction frommain.js. - Create an
asyncfunction,addBoosters, that throws some error:
async function addBoosters() {
throw new Error('Unable to add Boosters');
} - Create an
asyncfunction,performGuidanceDiagnostic, that also throws an error...