AsyncGenerator.prototype.throw() - JavaScript | MDN
Syntax
js
asyncGeneratorInstance.throw(exception)
Parameters
Return value
If the thrown error is not caught, it will return a Promise which rejects with the exception passed in.
If the exception is caught by a try...catch and the generator resumes to yield more values, it will return a Promise which resolves with an Object with two properties:
Examples
Using throw()
The following example shows a generator and an error that is thrown using the throw method. An error can be caught by a try...catch block as usual.
js
// An async task. Pretend it's doing something more useful
// in practice.
function sleep(time) {
return new Promise((resolve, reject) => {
setTimeout(resolve, time);
});
}
async function* createAsyncGenerator() {
while (true) {
try {
await sleep(500);
yield 42;
} catch (e) {
console.error(e);
}
}
}
const asyncGen = createAsyncGenerator();
asyncGen.next(1).then((res) => console.log(res)); // { value: 42, done: false }
asyncGen
.throw(new Error("Something went wrong")) // Error: Something went wrong
.then((res) => console.log(res)); // { value: 42, done: false }
Specifications
| Specification |
|---|
| ECMAScript® 2027 Language Specification # sec-asyncgenerator-prototype-throw |