I'm so glad to see more interest in using generators in node.js.  I've
experimented with this style of programming a *lot*.  I even went so far as
to re-implement node.js in the lua language (luvit.io) and attempted to
implement it on top of SpiderMonkey (luvmonkey) because both VMs already
have co-routines/generators.

I know this question has already been answered, but I wanted to share my
solution as I ran into the same issue using generators for some js-git
related examples.
https://github.com/creationix/git-repo/blob/master/example/create.js

The relevant part of that file is where I loop over nested objects and
create git history from them.  This involves I/O (and thus yielding) at all
levels of the nested loops.

run(function* main() {

  // Configure the repo API to work from a local clone.
  var repo = yield gitRepo({ fs: fs("./test-repo.git"), bare: true,
init: true });
  console.log("Git database Initialized");


  var parent;
  yield* each(commits, function* (message, files) {
    // Start building a tree object.
    var tree = {};
    yield* each(files, function* (name, contents) {
      // Save the file in the database and store the hash in the tree data.
      tree[name] = {
        mode: 0100644,
        hash: yield repo.save({
          blob: {
            length: contents.length,
            source: create(contents)
          }
        })
      };
    });
    var commit = {
      tree: yield repo.save({tree: tree}),
      parent: parent,
      author: author + " " + gitDate(new Date),
      committer: committer + " " + gitDate(new Date),
      message: message
    };
    if (!parent) delete commit.parent;
    parent = yield repo.save({commit: commit});
    yield repo.updateHead(parent);
  });

});

// Generator friendly forEach for objects
function* each(object, callback) {
  var keys = Object.keys(object);
  for (var i = 0, l = keys.length; i < l; i++) {
    var key = keys[i];
    yield* callback(key, object[key]);
  }
}


As you can see, I had to create a simple "each" helper that worked like
forEach, but worked in terms of yielding generators.

P.S.  I know you were hoping for the community to standardize on one helper
soon, but I feel it's far to premature for that.  Generators don't work in
any stable release of node and even the unstable releases require a flag to
use it.  There is more to explore in this area, especially generator based
streams once they land in a stable release and not behind a flag.

P.P.S I too wrote a simple generator helper based on the gist I wrote that
galaxy is inspired from.  Mine is called "gen-run"
https://github.com/creationix/gen-run. Another one that seems popular is
TJ's "co" https://github.com/visionmedia/co

-Tim Caswell




On Mon, Jul 15, 2013 at 2:11 AM, cpprototypes <cpprototy...@gmail.com>wrote:

> Thanks for the replies, I have a better understanding now of how these
> libraries are using generators.  I hope that one of these types of
> libraries becomes as popular as the async library and "standard" within the
> node community.  This way of writing async code is much more elegant than
> the current way of using only callbacks and can help expand node.js usage
> into other areas.  For instance, the script example I wrote is part of a
> larger command line script I was writing to test some services.  Such
> scripting tends to follow a synchronous flow.  I got really frustrated
> while writing it in an async way (since the natural flow is synchronous, it
> maps very poorly to the current callback-only style, even libraries like
> async don't help much).  I eventually gave up and quickly wrote the script
> in python because I had to get the task done for the day.  But I want
> node.js to eventually take python's place in my tool set.  So I went back
> and tried it again with this new generators feature and it was going well
> until I ran into this issue.  Some may say that such use is beyond the
> scope of node.js, but I think JS and node.js have potential to be more than
> just network async programming.
>
>
>
> On Friday, July 12, 2013 2:47:28 PM UTC-7, cpprototypes wrote:
>>
>> I'm using node 0.11.3 with --harmony-generators to try the new feature.
>>  I found two libraries that should help use existing node callback-based
>> code with generators (suspend and galaxy).  The code I'm trying to run was
>> similar to the following:
>>
>> (using suspend)
>>
>> var fs = require('fs');
>> var request = require('request');
>>
>> suspend(function* (resume) {
>>     var contents = yield fs.readFile('idList.json', 'utf8', resume);
>>     contents.split('\n').forEach(**function(id) {
>>         var info = yield 
>> request.get('http://www.**example.com?id='+id<http://www.example.com?id='+id>,
>> resume);
>>     });
>> })();
>>
>> (using galaxy)
>>
>> var galaxy = require('galaxy');
>> var fs = galaxy.star(require('fs'));
>> var request = galaxy.star(require('request')**);
>>
>> function* main() {
>>     var contents = yield fs.readFile('idList.json', 'utf8');
>>     contents.split('\n').forEach(**function(id) {
>>         var info = yield 
>> request.get('http://www.**example.com?id='+id<http://www.example.com?id='+id>
>> );
>>     });
>> };
>>
>> galaxy.unstar(main)(function(**err, result) {
>>     console.log('done');
>> });
>>
>> Using either library, when node tries to execute the get request ("var
>> info = yield request.get...") it exits with the following error:
>>
>> SyntaxError: Unexpected identifier
>>
>> And the error highlights the "request" part in "var info = yield
>> request.get..."  I'm guessing that the creation of the new function scope
>> in the forEach is somehow causing an issue.  But I'm not sure why it's not
>> working.
>>
>>
>>  --
> --
> Job Board: http://jobs.nodejs.org/
> Posting guidelines:
> https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
> You received this message because you are subscribed to the Google
> Groups "nodejs" group.
> To post to this group, send email to nodejs@googlegroups.com
> To unsubscribe from this group, send email to
> nodejs+unsubscr...@googlegroups.com
> For more options, visit this group at
> http://groups.google.com/group/nodejs?hl=en?hl=en
>
> ---
> You received this message because you are subscribed to the Google Groups
> "nodejs" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to nodejs+unsubscr...@googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>
>

-- 
-- 
Job Board: http://jobs.nodejs.org/
Posting guidelines: 
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
You received this message because you are subscribed to the Google
Groups "nodejs" group.
To post to this group, send email to nodejs@googlegroups.com
To unsubscribe from this group, send email to
nodejs+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/nodejs?hl=en?hl=en

--- 
You received this message because you are subscribed to the Google Groups 
"nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to nodejs+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to