Error Handling in Asynchronous JavaScript With try/catch Blocks

By Hemanta Sundaray on 2023-02-02

The async and await keywords in JavaScript allow you to write asynchronous code that looks and behaves like synchronous code.

When you use async before a function declaration, you tell JavaScript that this function returns a promise and can be "awaited". When you use the await keyword before a promise, JavaScript will pause the execution of the code until the promise is resolved or rejected.

With the use of async and await, you can use ordinary try/catch blocks around asynchronous code, just like you would with synchronous code.

Here's an example:

async function fetchData() {
  try {
    const response = await fetch("https://api.example.com/data")
    const data = await response.json()
    return data
  } catch (error) {
    console.error("There was a problem fetching the data:", error)
  }
}

In this example, we declare an asynchronous function called fetchData(). Inside the function, we use the await keyword to wait for the result of the fetch() function and the response.json() method. If either of these promises are rejected, the error will be caught by the catch block and logged to the console. If everything goes well, the data is returned.

If you were to handle errors using promise .then methods instead of a try/catch block, the code would look like this:

function fetchData() {
  return fetch("https://api.example.com/data")
    .then(response => response.json())
    .then(data => {
      return data
    })
    .catch(error => {
      console.error("There was a problem fetching the data:", error)
    })
}

In this example, we handle errors by chaining a .catch method to the end of the promise chain. If any of the promises in the chain are rejected, the control flow jumps directly to the .catch block and the error is logged to the console.

The main difference between using try/catch blocks and .catch methods is the way the code looks and behaves. try/catch blocks make asynchronous code look and behave like synchronous code, making it easier to understand and debug. On the other hand, using .catch methods to handle errors can result in a more verbose and harder-to-follow codebase, especially if there are multiple promises involved.

Join the Newsletter