I have a generator being returned to me by a function call from a library I'm using. I then pass this generator to a function which iterates through it and does a bunch of logic on each of the items. I then want to refer to this same generator after that function has been called. However, it seems the generator no longer has/generates any items. The code is along these lines:
let myGenerator = this.generatorFunc();
console.log(Array.from(myGenerator).length); //prints N which is specified elsewhere
this.iterateThroughGenerator(myGenerator);
console.log(Array.from(myGenerator).length); //now prints 0 when I need it to be N still
iterateThroughGenerator(generator) {
for(let element of generator) {
// do a bunch of stuff with element
}
}
Once the generator function is completed, then you have to call this.getGeneratorFunc() to recreate the generator again. Also, when you do Array.from(myGenerator), it will complete that generator as well, so when you call this.iterateThroughGenerator(myGenerator) then nothing will occur because there are no elements being returned from the generator anymore. So you can either save the result of the generator into an array and reuse that array, or call this.getGeneratorFunc() three times for each time you want to get elements from it. In this specific example, I would do
Check out this answer as well. Previous Answer
Id also read this.