caco
Generator based control flow that supports both callbacks and promises.
npm install caco
Many existing flow-control libraries such as co, assume 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.
caco(fn*, cb)
caco(fn*).then(...).catch(...)
Resolves a generator function.
Accepts optional arguments and callback, or returns a promise if callback not exists.
var caco = require('caco')
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)
...
}).catch(function (err) {
})
Yieldable callback works by supplying an additional next
argument. Yielding non-yieldable 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.
var fn = caco.wrap(fn*)
Wraps a generator function into regular function that optionally accepts callback or returns a promise.
var fn = caco.wrap(function * (arg1, arg2, next) {
yield setTimeout(next, 1000)
return yield Promise.resolve(arg1 + arg2)
})
fn(167, 199, function (err, val) { ... })
fn(167, 689)
.then(function (val) { ... })
.catch(function (err) { ... })
caco.wrapAll(obj)
Wraps generator function properties of object:
function App () { }
App.prototype.fn = function * (next) {...}
App.prototype.fn2 = function * (next) {...}
caco.wrapAll(App.prototype)
var app = new App()
app.fn(function (err, val) {...})
app.fn2().then(...).catch(...)
Yieldable
By default, the following objects are considered yieldable:
Promise
Observable
Generator
It is also possible to override the yieldable mapper,
so that one can yield pretty much anything.
caco._yieldable = function (val, cb) { }
caco._yieldable = function (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
}
return false
}
caco(function * () {
console.log(yield [
Promise.resolve(1),
Promise.resolve(2),
3
])
try {
yield 689
} catch (err) {
console.log(err.message)
}
}).catch(function (err) {
})
Aggregated Yield
Multiple results can be aggregated in one yield
by using Promise.all
or callback-all.
var caco = require('caco')
var cball = require('callback-all')
caco(function * (next) {
var promises = [
asyncFn1(),
asyncFn2()
]
console.log(yield Promise.all(promises))
var all = cball()
asyncFn1(all())
asyncFn2(all())
console.log(yield all(next))
}).catch(function (err) {
})
License
MIT