The following example shows a simple generator and an error that is thrown using the throw
method. An error can be caught by a try...catch
block as usual.
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));
asyncGen
.throw(new Error("Something went wrong"))
.then((res) => console.log(res));