Retrieving generator references

Nicholas C. Zakas standards at
Sat Nov 22 16:55:20 PST 2014

After playing around with generators for most of the day (and pretty 
much loving all of it), I ended up with a code example for async that 
looks like this:

var fs = require("fs");

var task;

function readConfigFile() {
     fs.readFile("config.json", function(err, contents) {
         if (err) {
         } else {

function *init() {
     var contents = yield readConfigFile();

task = init();;

The thing that immediately jumped out at me was how poorly the `task` 
variable is being managed. So I was poking around trying to see if there 
was a way to get a reference to the generator instance from within the 
generator itself so I could pass it around, such as:

function *init() {
     var contents = yield readConfigFile(this);

Of course, `this` isn't a reference to the generator itself, but rather 
the this-binding for the function. It struck me, though, that my example 
could be a lot cleaner if I could get a reference to the generator from 
the generator function and pass that around rather than having to manage 
that reference outside.

Now to my question: is there a way to get a reference to the generator 
from inside the generator function?

(Also, sorry if I'm getting the nomenclature wrong, still trying to wrap 
my head around the relationship between generators, iterators, and 

Nicholas C. Zakas

More information about the es-discuss mailing list