published on in web
tags: javascript

Generators

Send messages to generators

function* createHello() {
    const name = yield
    console.log('Hello ' + name)
}

const hello = createHello()
hello.next();
hello.next('Riderman');

Throw errors inside of generators

function* createHello() {
    try {
        const name = yield
        console.log('Hello ' + name)
    } catch (error) {
        console.error(error); // OPS
    }
}

const hello = createHello()
hello.next();
hello.throw(new Error('Ops'));

Delegate generators interation control

function* create3to5Counter() {
    yield 3;
    yield 4;
}
function* createCounter() {
    yield 1;
    yield 2;
    yield* create3to5Counter(); // another generator
    yield 6;
}

for (let i of createCounter()) {
    console.log(i)
}