Is it possible to reset an ECMAScript 6 generator to its initial state?

前端 未结 8 1367
有刺的猬
有刺的猬 2020-12-01 12:19

Given the provided (very simple) generator, is it possible to return the generator back to its original state to use again?

var generator = function*() {
            


        
8条回答
  •  -上瘾入骨i
    2020-12-01 12:39

    If your intention is

    to some other scope, iterate over it, do some other stuff, then be able to iterate over it again later on in that same scope.

    Then the only thing you shouldn't try doing is passing the iterator, instead pass the generator:

    var generator = function*() {
        yield 1;
        yield 2;
        yield 3;
    };
    
    var user = function(generator){
    
        for (let x of generator()) {
            console.log(x);
        }
    
        for (let x of generator()) {
            console.log(x);
        }
    }
    

    Or just make a "round robin" iterator and check while iterating

    var generator = function*() {
        while(true){
            yield 1;
            yield 2;
            yield 3;
        }
    };
    
    for( x in i ){
        console.log(x);
        if(x === 3){
            break;
        }
    }
    

提交回复
热议问题