Motivation
starx allows you to use ECMAScript 6 generators to perform flow control. (The 'star' in the name is inspired from the declaration of a generator function, i.e. function*() {...}
while 'x' stands for 'executor'.)
Basically, no more callback hells with cumbersome exception handling...
With starx, you can write:
How it works
Invoking starx()
on a generator returns an executor. You can create multiple executors for the same generator instance.
This executor, when invoked, keeps calling generator.next()
until the generator is exhausted. Each call to generator.next()
returns the next value yielded (or returned) from inside the generator. For starx
to work, this value must be "yieldable", i.e. one of the followings:
- A functions whose only argument is a callback accepting (err, val) (see yieldable functions)
- A promise (anything with a then(callback, errback))
- A value (primitive, object, null)
- Another executor created by starx
- A generator or iterator
- An array of the aboves (nesting okay)
Yieldable functions
If a function takes more than one argument, you can use starx.yieldable(fn)
to convert it to a compliant form. For example:
If fn
is function(arg1, arg2, cb) {...}
, invoking starx.yieldable(fn)
returns a new function with the following form:
var { return {...}}
Invoking newFn(arg1, arg2)
returns a function accepting a callback, which as mentioned, is compliant with starx
and thus can be yielded, like so:
Most NodeJS functions (built-in and libraries) can be converted to a yieldable function using this approach.
Examples
Read file
starx = readFile = starx var { var content = console}var executor =
Or simply:
Serial download
starx = request = starx { return responses}
Parallel download
A DRYer version
You might think we could have written:
urls
But that wouldn't work. The reason is map
invoke request
with not just the element, but also its index and the original array. Because yieldable
passes through all arguments by default, request
would end up being invoked with those 3 arguments while it actually expects the second argument to be
a callback.
To make this work, either explicitly invoke request
with url
as the previous example or provide a second argument to yieldable
: argCount
. If argCount
is true, yieldable
limits the number of arguments passed through to be fn.length-1
. If argCount
is a number, yieldable
limits the number of arguments to be argCount-1
.
We can revise the previous example as follows:
request = starx.yieldable(require('request'), true /* argCount */)
starx(function*() {
var res = yield [urls].map(request)
console.log(size(res), "bytes")
})()
Install
NPM
npm install starx
Bower
bower install starx
- Node >= 0.11.6 (run with
--harmony
or--harmony-generators
) - Chrome >= 28 (turn on experimental flag)
- Firefox >= 27
- Or use Google Traceur