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

前端 未结 8 1338
有刺的猬
有刺的猬 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条回答
  • 2020-12-01 12:44

    I think this is not a concern of a generator, but of an iterator – which actually 'does the labour'. To reset an iteration you just need to create a new iterator. I would probably use a dumb higher order function like this:

    function *foo() {
        yield 1;
        yield 2;
        yield 3;
    }
    
    const iterateFromStart = (func) => {
        // every invocation creates a brand new iterator   
        const iterator = func();
        for (let val of iterator) {
            console.log(val)
      }
    }
    
    iterateFromStart(foo); // 1 2 3
    iterateFromStart(foo); // 1 2 3
    
    0 讨论(0)
  • 2020-12-01 12:48

    As per the draft version of ES6,

    Once a generator enters the "completed" state it never leaves it and its associated execution context is never resumed. Any execution state associated with generator can be discard at this point.

    So, there is no way to reset it once it is completed. It also makes sense to be so. We call it a generator, for a reason :)

    0 讨论(0)
提交回复
热议问题