Open In App

How to throw an error in an async generator function in JavaScript ?

Last Updated : 26 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will try to understand how to throw an error in a synchronous (abbreviated as “async”) generator function in JavaScript with the help of theoretical as well as coding examples.

Let us first have a look into the following section which will show us the syntax for declaring an async generator function.

Syntax:

async function* function_name () {
    ...
}

We will learn about the declaration of the async generator function and know how to throw an error in an async generator function.

Example 1: In this example, we will use the throw keyword for an error using an error object that will contain an error message passed in by the user as per requirement, and later we will catch that error using a catch statement.

Javascript




<script>
    async function* generator() {
        throw new Error("Error thrown from an "
            + "async generator function....!!!");
    }
  
    let iterator = generator();
  
    iterator
        .next()
        .then((result) => console.log(result.value))
        .catch((error) => console.log(error.message));
</script>


Output:

Error thrown from an async generator function....!!!

Example 2: In this example, we will use the yield keyword by which we will catch the error in the latter part of our code. Further, we will declare a promise whose state is in rejected one containing the error message in the reject() method inside it and then we will catch it using a catch statement.

Javascript




<script>
    async function* generator() {
        yield new Promise((resolve, reject) => {
            reject("Error thrown from an async "
                + "generator function....!!!");
        });
    }
  
    let iterator = generator();
  
    iterator
        .next()
        .then((result) => console.log(result.value))
        .catch((error) => console.log(error));
</script>


Output:

Error thrown from an async generator function....!!!


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads