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

前端 未结 8 1376
有刺的猬
有刺的猬 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:39

    No there is no going back to same state.

    To make it clear, you must understand the working of generator functions.

    When generator function gets called first time, it returns iterator(as its entire body). Initial status of this return iterator is get stored in its variables. Two very important variables are GeneratorStatus, GeneratorLocation.

    There are are other variables such as GeneratorFunction, GeneratorReceiver, Scopes. Which can ignored to understand this answer.

    So initial status will be, GeneratorStatus : suspended. GeneratorLocation: 1;

    Now to use iterator you should call it using .next(); Hence forth iterator will resume its execution from location pointed by 'GeneratorLocation'

    Now generator will update its value of GeneratorLocation to line no where it first yields the result and GeneratorLocation will be same until it returns last yield.

    Now for Each successive calls of .next, Generator will resume its execution from value of GeneratorLocation and not from the beginning.

    Hence, Unless you repeat the code in generator function, resetting to initial state is not possible. best solution is just recreate new iterator with params.

提交回复
热议问题