Access variable inside javascript function (generator)



In Javascript suppose I have a generator which i cannot modify the source code of. I iterate through a couple of times and now want to look inside at the variables of the generator. How can I do this without changing the code of the generator itself? More concretely –

async function* myGen(){
    while (true){
        let a = something
        yield something_else
    } 
}

let gen = myGen()

for await (const data of gen){
    if(data === special_value){
        let my_a = get_value_of_a(gen) // this is the function i want
    }
}

Answer

If the generator doesn’t yield the value of a (or something that gives you access to the value of a), you cannot access it. a is a local variable within the generator function. It’s not accessible from outside that function (unless you do something to make it accessible, but you said you can’t modify the generator function).

Putting it another way: The value of a is private information held inside the generator object the function returns. You can’t access that private information if the generator object doesn’t provide a means of doing so, which the ones created by generator functions don’t by default.



Source: stackoverflow