caco
Generator based control flow that supports both callbacks and promises.
Many existing flow-control libraries such as co, assumes promises to be the lowest denominator of async handling.
Callback functions require promisify to be compatible, which creates unnecessary complication.
In caco, both callbacks and promises are yieldable.
Resulting function can also be used by both callbacks and promises.
This enables a powerful control flow while maintaining simplicity.
npm install caco
var fn = caco(fn *)
var caco = require('caco')
var fn = caco(function * (next) {
try {
yield Promise.reject('boom')
} catch (err) {
console.log(err)
}
var foo = yield Promise.resolve('bar')
yield setTimeout(next, 1000)
var data = yield fs.readFile('./foo/bar', next)
return data
})
fn(function (err, res) { })
fn().then(...).catch(...)
To enable yieldable callbacks, yielding non-promise-nor-generator value pauses the current generator.
Until next(err, val)
being invoked by callback,
where val
passes back to yielded value, or throw
if err
exists.
Yieldables
By default, the following objects are supported for yield
:
Promise
Observable
Generator
Caco also accepts a yield mapper function,
so that one can basically yield anything.
var fn = caco(fn *, mapper)
function mapper (val, cb) {
if (Array.isArray(val)) {
Promise.all(val).then(function (res) {
cb(null, res)
}, cb)
return true
}
if (val === 689) {
cb(new Error('DLLM'))
return true
}
}
caco(function * () {
console.log(yield [
Promise.resolve(1),
Promise.resolve(2),
3
])
try {
yield 689
} catch (err) {
console.log(err)
}
}, mapper)(function (err) { })
License
MIT