Open In App

Javascript AsyncGenerator.prototype.throw() Method

Last Updated : 07 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

JavaScript AsyncGenerator.prototype.throw() method is used with asynchronous generators to throw an exception into the generator and handle it within the generator function. It returns a Promise that resolves to an object with two properties: value and done.

Syntax:

AsyncGenerator.prototype.throw(exception)

Parameters: The throw() method accepts only one parameter as shown in the above syntax and explained below:

  • exception: It is the exception to be thrown into the generator. This can be any value such as an error object or a custom exception.

Return Value: The return value is an object representing the completion of the generator. It has two properties:

  • value: The resolved value of the generator.
  • the A boolean value, that indicates whether the generator has completed or not.

The below examples will help you understand the practical implementation of the throw() method of the asyncGenerator() function.

Example: The below example will illustrate the use of the throw() method practically.

Javascript




async function* asyncGenerator() {
    try {
        yield 1;
        yield 4;
        yield 6;
    } catch (error) {
        console.log('Caught:', error);
    }
}
const generator = asyncGenerator();
generator.next().then(result => {
    console.log(result.value);
    console.log(result.done);
});
generator.throw(new Error(
    'Something went wrongs')).then(result => {
    console.log(result.value);
    console.log(result.done);
});


Output

Caught: Error: Something went wrongs
    at Object.<anonymous> (/home/guest/sandbox/Solution.js:15:17)
    at Module._compile (node:internal/modules/cjs/loader:1198:14)
    at Object.Module._extension...

Example 2: Below example will illustrate how you can handle errors in an Asynchronous Generator.

Javascript




async function* GFG() {
    try {
        yield 1;
        yield 2;
        yield 3;
    } catch (error) {
        console.error(
            "Generator caught an error:", error);
    }
}
const generator = GFG();
(async () => {
    console.log(await generator.next());
     
    // { value: 1, done: false }
    console.log(await generator.throw(
        new Error("Custom error")));
         
    // Generator caught an error: Error: Custom error
})();


Output:

{ value: 1, done: false }
ERROR!
Generator caught an error: Error: Custom error
at /tmp/0NKyhi2aPF.js:14:37
{ value: undefined, done: true }

Supported Browsers: The browsers supported by Generator.prototype.throw() method are listed below: 

  • Google Chrome 39 and above
  • Firefox 26 and above
  • Opera 26 and above
  • Safari 10 and above
  • Edge 13 and above


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads