It just goes to show how good promises are for this kind of problem. I’d
probably promisify `readFile` and use `Q.spawn()`.
The best I could come up with for Node.js-style callbacks was the following
code.
```js
var fs = require("fs");
function *init() {
var nextFunc = yield;
var contents = yield fs.readFile("config.json", nextFunc);
doSomethingWith(contents);
console.log("Done");
}
var task = init();
task.next();
task.next(nextify(task));
function nextify(myTask) {
return function(error, result) {
if (error) {
myTask.throw(error);
} else {
myTask.next(result);
}
};
}
```
> On 23 Nov 2014, at 01:55, Nicholas C. Zakas <[email protected]>
> wrote:
>
> 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) {
> task.throw(err);
> } else {
> task.next(contents);
> }
> });
> }
>
> function *init() {
> var contents = yield readConfigFile();
> doSomethingWith(contents);
> console.log("Done");
> }
>
> task = init();
> task.next();
> ```
>
> 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);
> doSomethingWith(contents);
> console.log("Done");
> }
> ```
>
> 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 functions.)
--
Dr. Axel Rauschmayer
[email protected]
rauschma.de
_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss