How it works...

When we await a result from an asynchronous function that fulfills with an error state, an error is thrown. To continue with the program, we need to catch this error. In the preceding recipe, the first asynchronous function throws so the second operation isn't performed, then we log the error to the console before exiting the try-catch block.

This compares favorably with Promise chain error handling, which uses the same try-catch mechanism for error handling as synchronous code. We don't need to wrap synchronous code with promises so that they can work with Promise.catch; we can use the language level try-catch blocks.

In the next recipe, we'll see how try-catch works with multiple asynchronous operations operating concurrently. ...

Get ECMAScript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.