engen
The generator engine.
Async control flow using pure ES6 generators.
Requires ES6 generator support. Tested on Node 0.12 with the --harmony
flag.
yield
Async code based on With generators, calling an asynchronous function and waiting for its result is
as simple as calling yield f()
. Parameters and return values work exactly as if
the code were synchronous.
var g = ; { g; return x;} { return ; // takes 1000ms} { var b = ; return 'a' + b;} g;
Yielding an array of generators will run them in parallel and return an array of ordered results.
var g = ; { g; return 'a';} { g; return 'b';} { return ; // takes 2000ms} g;
Yielding an object of generators behaves identically to yielding an array, but the resulting value is an object.
var g = ; { g; return 'a';} { g; return 'b';} { return a: b: ; // takes 2000ms} g;
Inside collections, mixing generators and simple values is allowed. Generators will be waited for, anything else will be passed through untouched.
Note: this includes objects and arrays: be careful not to nest collections of generators.
var g = ; { g; return 'a';} { return false null {};} g;
Exceptions also behave as if the code were synchronous:
var g = ; { g; throw Error'oops';} { try ; // takes 1000ms catcherr console // 'Error: oops' return 'a';} g; g;
API
engen.run()
Run generator based code from callback-land.
var g = ; { g; return 'done';} g;
engen.wrap()
Wrap callback-style code and call it from generator-land.
var g = ;var readFile = g; { g; return ;} g;
By default, wrap()
expects callbacks to have the standard Node signature:
{}
To wrap an unusual callback, you can pass in a function as a second parameter
to wrap()
to perform custom handling of the callback parameters.
To handle multiple return values and return them as an array:
var g = ; var f = g;
To handle callbacks without an err
parameter:
var g = ; var f = g;
For your convenience, these two handlers are built in, as g.multipleReturnCallback
and g.noErrorCallback
.
engen.wait()
Generator-based version of setTimeout
, provided for convenience.
var g = ; { g; // pauses for 1000ms return 'done';} g;
License
MIT