Open In App

Why is it possible to try-catch an async-await call ?

Improve
Improve
Like Article
Like
Save
Share
Report

JavaScript’s try-catch is used to handle errors and exceptions that occur when an error occurs during execution also called runtime error. The ‘async’ and ‘await’ are keywords in JavaScript that are used to write asynchronous code. The async keyword is used to declare an asynchronous function, which is a function that returns a promise and can be awaited. Asynchronous functions are used to perform long-running tasks in the background, such as making network requests or reading from a file, without blocking the main thread of execution.

The await keyword is used inside an asynchronous function to pause the execution of the function until a promise is resolved. It allows you to write asynchronous code in a synchronous-like style, making it easier to read and write. Using async and await makes it easy to write asynchronous code that is simple and easy to understand, without the need for callback functions or complex promise chains. Let’s understand with the example. 

Example:

 

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>
        Why is it possible to try-catch 
        an async-await call ?
    </title>
</head>
  
<body>
    <span>Click the button</span>
  
    <button onclick="getData()">
        Click here
    </button>
      
    <script>
        async function getData() {
            const rollnodata = await report1;
            console.log(rollnodata);
            const biodatas = await getnames(rollnodata[1]);
            console.log(biodatas);
            return biodatas;
        }    
    </script>
</body>
  
</html>


Output:

output without try catch

It is possible to use a try-catch block to handle errors that might occur in an asynchronous function that uses the await keyword. This is because the await keyword causes the function to pause and wait for the asynchronous operation to complete, and any errors that occur during the asynchronous operation can be caught in a try-catch block just like any other synchronous code. Consider the following asynchronous function that performs an HTTP request using the fetch function and awaits the response:

async function fetchData() {
    try {
        const response = await fetch('http://...com/data');
        const data = await response.json();
        console.log(data);
      } catch (error) {
        console.error(error);
      }
}

index.html

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>
        Why is it possible to try-catch
        an async-await call ?
    </title>
</head>
  
<body>
    <span>Click the button</span>
  
    <button onclick="getData()">
        Click here
    </button>
      
    <script>
        async function getData() {
            try {
  
                const rollnodata = await report1;
                console.log(rollnodata);
                const biodatas = await getnames(rollnodata[1]);
                console.log(biodatas);
                return biodatas;
            }
            catch (error) {
                console.log(`The error is: ${error}`);
            }
        }
    </script>
</body>
  
</html>


Output:

Output after using try-catch

Explanation: If the fetch function encounters an error (e.g., the URL is invalid or the server returns a 404 status code), the error will be caught in the catch block and can be handled appropriately. It is important to note that the try-catch block will only catch errors that occur during the asynchronous operation itself (e.g., the fetch function in this example). It will not catch errors that occur before the asynchronous operation is started (e.g., if the URL is null) or after the operation has been completed (e.g., if the returned data is in an invalid format).



Last Updated : 30 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads