[Javascript] Delegate JavaScript (ES6) generator iteration control

We can execute generators from generators, and delegate the iteration control with the yield* keyword.

Yo dawg, I heard you like generators, so I put generators inside your generators.

 

 
function* create3To4Counter() {
    yield 3;
    return 4;
}

function* createCounter() {
    yield 1;
    yield 2;
    const four = yield* create3To4Counter();
    console.log("four", four)
    yield 5;
}

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

/*
1
2
3
4
5
*/

 

posted @ 2018-02-06 21:01  Zhentiw  阅读(163)  评论(0编辑  收藏  举报