A tiny ES6 (harmony) library for node 0.11.2+ that helps you use generators with node style callbacks.
An ES6 (harmony) library for node 0.11.2 and up that helps you use generators with node style callbacks, similar to suspend
Spawn a generator task. From within your task, call your async functions with yield. Instead of a callback function, pass them a generated resume function:
Genny automatically passes
resume as the last argument to your generator.
Its a constructor that can make resume callbacks.
The generator pauses when it encounters a yield, then resumes when the created resume callback is called by the async operation. If the callback was called with a value:
then the yield expression will return that value.
You can handle errors with
catch, or as return results via
Alternatively, you can pass a callback argument to
If you need to run multiple operations in parallel, don't yield immediately:
The order of yield results is guaranteed to be the same as the order of the
resume() callback constructors. Feel free to use it in loops too:
You may also give yield a thunk (a function that take callback) or a promise
or an array of these which will be run in parallel.
You can also use
genny.fn instead to create a function which
can accept multiple arguments and a callback. The arguments will be
passed to your generator, but instead of the callback, you will get
var getLine = genny;;
The result is a function that takes the specified arguments plus a standard node style callback. If you return a value at the end of your generator, it is passed as the result argument to the callback.
If the async function calls the callback with more than 2 arguments, an array will be returned from the yield expression:
resume.gen() to call a genny-compatible generator:
yield* someGenerator(args..., resume.gen())
genny.fn creates a callback-taking node function which requires its last
argument to be a callback. To create a listener function use
Listeners currently ignore all errors and return values, but this may change in the future.
To create an express or connect middleware that properly forwards errors,
genny comes with longStackSupport that enables you to trace errors across generators. Simply write:
longStackSupport = true
to get stack traces like these:
Error: oopsat Object._onImmediate (/home/spion/Documents/genny/test/index.js:10:12)at processImmediate [as _immediateCallback] (timers.js:325:15)From generator:at innerGenerator1 (/home/spion/Documents/genny/test/index.js:136:26)at innerGenerator2 (/home/spion/Documents/genny/test/index.js:139:43)at innerGenerator3 (/home/spion/Documents/genny/test/index.js:142:43)at Test.completeStackTrace2 (/home/spion/Documents/genny/test/index.js:145:43)
for code like this:
This results with CPU overhead of approximately 100% and memory overhead of approximately 80%.
In the future, the overhead will probably be eliminated in node but not in browsers.
test/index.js for more examples and tests.