Open In App

Javascript AsyncGenerator.prototype.throw() Method

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:



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

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.




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.




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: 


Article Tags :