Awesome
make-callback
Make synchronous function or generator to support callback api
Install
npm i make-callback --save
npm test
Usage
For more use-cases see the tests
var makeCallback = require('make-callback')
var JSONParseAsync = makeCallback(JSON.parse)
JSONParseAsync('{"foo":"bar"}', function (err, json) {
if (err) {
return console.error(err)
}
console.log(json)
//=> {foo: 'bar'}
})
You also can make generator that return and yield anything (string, array, object, function, thunk, promise or etc) to support callback api
var fs = require('mz/fs')
var makeCallback = require('make-callback')
function * gen (val) {
var a = yield 'a'
var b = yield {b: 'b'}
var c = yield ['c', 'f']
var d = yield 123
var e = yield fs.readFile('./package.json')
return [a, b, c, d, e, val || 'foobar']
}
var genCallback = makeCallback(gen)
genCallback(function (err, res) {
if (err) {
return console.error(err)
}
console.log(res)
//=> ['a', {b: 'b'}, ['c', 'f'], 123, 'content of package.json', 'foobar']
console.log(res.length)
//=> 6
})
See aslo
- manage-arguments: Prevents arguments leakage - managing arguments. From Optimization killers by Petka Antonov.
- handle-arguments: Handles given Arguments object - return separatly last argument (commonly callback) and other arguments as Array. Useful in node-style callback flow.
- handle-callback: Make promise to have support for callback api, it returns promise in that same time.
- always-callback: Create callback api for given sync function. Guarantee that given function (sync or async, no matter) will always have callback api and will handle errors correctly.
- always-thunk: Create thunk from async or sync function. Works like
thunkify
. - always-promise: Create Bluebird Promise from given async or synchronous function. It automatically convert sync functions to async, then to promise.
- is-es6-generator: Check that given value is Generator
Contributing
Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.
But before doing anything, please read the CONTRIBUTING.md guidelines.